expressjs 框架:实现跨域

说明

跨域的方式有两种:

  • 手动实现,适用于实现简单跨域

  • 使用中间件,适用于复杂功能

手动实现

// 跨域
app.all('*', function(req, res, next) {
    const origin = req.headers['origin']
    // 允许跨域源
    res.header("Access-Control-Allow-Origin", origin);
    // 允许跨域请求头
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    // 允许跨域方法
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
});

完整代码

// 引入 express 模块
const express = require('express');
// 创建 express 对象
const app = express();
// 指定监听端口
const port = 8081;


// 跨域
app.all('*', function(req, res, next) {
    const origin = req.headers['origin']
    // 允许跨域源
    res.header("Access-Control-Allow-Origin", origin);
    // 允许跨域请求头
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    // 允许跨域方法
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
});


app.post('/getUser', (req, res) => {
   // 发送内容
   const data = {
       code: 0,
       data: {
           "name":"李雷",
           "role":"VIP",
           "sex":"male"
       }
   };
   res.json(data);
})

// 启动服务,监听端口
const server = app.listen(port, function () {

  // var host = server.address().address
  // var port = server.address().port

  console.log("服务启动成功,监听端口是", port)

})

原文出处:/show_1GWNm7oX535.html