Express 4接受POST请求的body数据

    科技2022-07-13  135

    第一种方式:

    // AJAX请求 $.ajax({ type: 'POST', url: 'http://127.0.0.1:3000/', data: JSON.stringify({ username: 'xt', age: 15 }), contentType: 'application/json' }); const express = require('express'); const app = express(); app.use(express.json({type: 'application/json'})); //跨域设置(所有域名) app.all('*', function (req, res, next) { //其中*表示允许所有域可跨 res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Methods', '*'); res.header('Content-Type', 'application/json;charset=utf-8'); next(); }); app.post('/', (req, res, next) => { console.log(req.body); res.send('Hello World!'); }); app.listen(3000, () => { console.log('项目已在3000端口启动....'); });

    第二种方式:

    $.ajax({ type: 'POST', url: 'http://127.0.0.1:3000/', data: { username: 'xt', age: 15 }, contentType: 'application/x-www-form-urlencoded' }); const express = require('express'); const app = express(); // app.use(express.json({type: 'application/json'})); app.use(express.urlencoded({extended: true})); //跨域设置(所有域名) app.all('*', function (req, res, next) { //其中*表示允许所有域可跨 res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Methods', '*'); res.header('Content-Type', 'application/json;charset=utf-8'); next(); }); app.post('/', (req, res, next) => { console.log(req.body); res.send('Hello World!'); }); app.listen(3000, () => { console.log('项目已在3000端口启动....'); });

     

    Processed: 0.009, SQL: 8