首先我在app.js中容許了全部請求express
// 容許全部的請求形式 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
POST請求和GET請求不太同樣,req.query獲取不到傳過來的參數,所以須要在app.js中使用json解析中間件(body-parser)npm
installjson
npm install body-parser
requireapp
// 引入json解析中間件 var bodyParser = require('body-parser');
usepost
// 添加json解析 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false}));
POST請求ui
var express = require('express'); var router = express.Router(); router.post('/', function(req, res, next) { // 獲取參數 var query = req.body; console.log("post請求:參數", query); res.send('hello , world'); });