基于node.js快速搭建本地服务器以模拟后端接口数据

一、准备工作

  • 安装 Node.js
  • 安装 Express.js
npm install express body-parser cookie-parser

二、编写服务器代码

创建名为 mockServer.js 的文件,添加以下代码:

const express = require('express');
const app = express();
//引入 body-parser 和 cookie-parser 中间件。解析客户端发送的请求体和客户端发送的 Cookie。
const bodyParese = require('body-parser');
const cookieParse = require('cookie-parser');

app.use(cookieParse());
app.use(bodyParese.urlencoded({ extended: false }));
app.use(express.static('public'));

//CORS(跨源资源共享)策略。允许任何来源 (origin) 的请求,并允许携带凭证(例如 Cookie)。
app.all('*', function (req, res, next) {
    const origin = req.headers.origin;
    res.header('Access-Control-Allow-Origin', origin);
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Lenght,Authorization,ACcept,X-Requested-With,yourHeaderFeild');
    if (req.method == 'OPTIONS') {
        res.send(200);
    } else { next(); }
})

app.get('/userData/BasicInfo',(req,res)=>{
    console.log(req.query);
    const response = {
        rescode:0,
        resmsg:'Success',
        data:{
            basicInfo:{
                name:'测试用户名',
                gender:'M',//M or F
                customerID:'12345678901234',
                age:30,
                address:'测试地址'
            },
            accountInfo:{
                totalScore:86.35,
                mainAccountScore:90.02
            }
        }
    };
    res.end(JSON.stringify(response));
})

//启动服务器
const PORT = process.env.PORT || 8080;
app.listen(PORT,()=>{
    console.log(`MOCK Server 正在监听${PORT}端口...`);
})

三、运行服务器

  1. 在对应目录的终端中运行以下命令启动服务器:
    node mockServer.js
  2. 打开浏览器或使用其他工具访问 http://localhost:8080/userData/BasicInfo 来测试接口。

排错:当代码为res.header('Access-Control-Allow-Origin', '*'); 会报错 The value of the ‘Access-Control-Allow-Origin‘ header in the response must not be the wildcard ‘*’

原因:

服务端接到请求后,就可以根据传过来的Origin头做逻辑,决定是否要将资源共享给这个源。而这个决定通过响应头Access-Control-Allow-Origin来承载,它的value值可以是任意值,有如下情况:

  1. 值为*,通配符,允许所有的Origin共享此资源
  2. 值为http://localhost:5432(也就是和Origin相同),共享给此Origin
  3. 值为非http://localhost:5432(也就是和Origin不相同),不共享给此Origin
  4. 无此头:不共享给此origin
  5. 有此头:值有如下可能情况

然而,当 Access-Control-Allow-Credentials 设置为 true 时,不允许使用通配符 *。这是因为当请求携带了凭证(如 Cookie、HTTP 认证等)时,浏览器为了安全考虑,要求明确指定允许哪些源进行跨域请求。当 Access-Control-Allow-Credentials 设置为 true 时,Access-Control-Allow-Origin 必须是一个具体的域名(而不是通配符 *),以确保只有特定的站点才能访问这些包含凭证的资源。

解决方法

指定允许的源:将 Access-Control-Allow-Origin 设置为前端应用所在的域名。

你可能感兴趣的:(node.js,前端)