利用 node Express 框架实现get,post请求的前后端交互

安装 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);
    }
})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值