Express踩坑系列之POST請求


首先我在app.js中允許了所有請求

// 允許所有的請求形式 
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)

install

npm install body-parser

require

// 引入json解析中間件
var bodyParser = require('body-parser');

use

// 添加json解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

POST請求

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');
});

 


免責聲明!

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



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