安装 Express 并将其保存到依赖列表中:
$ npm i express -S
body-parser - node.js 中间件,用于处理 JSON, Raw, Text 和 URL 编码的数据。
$ npm i body-parser -S
node后台代码 node.js
const express = require('express');
const bodyParser = require('body-parser'); //为了获取post请求的参数
const app = express();
// app.all('*', function (req, res, next) {
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
// res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// res.header("X-Powered-By", ' 3.2.1')
// //这段仅仅为了方便返回json而已
// res.header("Content-Type", "application/json;charset=utf-8");
// if (req.method == 'OPTIONS') {
// //让options请求快速返回
// res.sendStatus(200);
// } else {
// next();
// }
// });
// 创建 application/json 解析器
app.use(bodyParser.json());
// 创建 application/x-www-form-urlencoded 解析器
app.use(bodyParser.urlencoded({ extended: false }));
//所有请求先走这里
app.use((req, res, next) => {
// console.log(req.get('Host')); //请求来自于
// console.log(req.url); //请求的资源
next();
})
app.post('/saveData', (req, res) => {
let getObj = req.body;
console.log(getObj);
res.send(JSON.stringify(getObj));
})
app.get('/getData', (req, res) => {
let getObj = req.query;
console.log(getObj);
res.send(JSON.stringify(getObj));
})
const server = app.listen(8081, () => {
const host = server.address().address;
const port = server.address().port;
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
启动后台 node node.js
前台发送请求:
POST请求
$.ajax({
type: 'post',
dataType: 'json',
url: 'http://localhost:8081/saveData',
data: {
name: 'zhang',
gongzi: '200000'
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
})
GET请求
$.ajax({
type: 'get',
dataType: 'json',
url: 'http://localhost:8081/getData',
data: {
name: 'zhang',
gongzi: '200000'
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
})