搭建vue+express项目
1.express建一个 server.js
// Setup basic express server
var express = require('express');
var compression = require('compression')
var bodyParser = require('body-parser');
var app = express();
app.use(compression());
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(bodyParser.json());
app.use(function(err, req, res, next) {
if (err) {
console.error(err.stack);
res.status(500).send({
error: 'Something failed!'
});
} else {
next(err, req, res, next);
}
})
app.use('/', require('./routes/routes'));// routes.js 里面写 api路由设置
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Server listening at port %d', port);
});
2.vue-cli 建立项目
1. npm install cue-cli webpack
2. vue init webpack vueTest(项目名字)
3.npm install
4.npm run dev
3.设置config中index的proxyTable
proxyTable: {
'/api/*': {
target: 'http://127.0.0.1:3000/',
preserveHost: false
}
},
assetsPublicPath: './',
这样就可以请求express中的api 了。ok
4.在前端vue文件中调用
可以用fetch或者是axios 在vue项目中的mai.js中添加fetch or axios : Vue.ProtoType.fetch = fetch.
this.axios.post("/api/users/login", { name: this.name, password: this.pwd }); this.fetch('/api/users/login',{ headers: { Accept: "application/json, text/plain, */*", "Content-Type": "application/json" }, method: "POST", body: JSON.stringify({ //参数 }) })