搭建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({
     //參數
   })
})

  

 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM