express

快速搭建本地服务

//创建服务实例
var express = require('express');
var app = express();
//引入body解析,否则req.body会是undefined
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//路由守卫,不需要每个接口都设置响应头了
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); //允许跨域
    res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With");
    next()
})
//post接口
app.post('/', function(req, res){
    //允许跨域,改在app.all()中
    //res.header("Access-Control-Allow-Origin","*");

    //前端的请求参数
    var reqbody = req.body

    var a=[
        {
            "fieldID":[
                "1"
            ],
            "protocolId":"1564368356"
            ,"value":1
        },
        {
            "fieldID":[
                "2"
            ],
            "protocolId":"1564368356"
            ,"value":2222
        }
    ]
  //返回值
  res.send({list:a});
});

0929

今天想调试分页的功能,但是后台还么做好。只能自己模拟接口了,前端需要传from,num的参数。神奇的是,突然就报错了,前一秒还好好的,而且是跨域错误


什么鬼,我明明就已经设置了

res.header("Access-Control-Allow-Origin", "*"); //允许跨域

仔细一看,咦,Access-Control-Allow-Headers?
网上一搜,有说要改前端axios配置的,不行,这个我是不能随意改的,毕竟项目不是我一个人在做。再一搜,咦这句好像有点像解决方案,毕竟报错就说Content-Type不在Access-Control-Allow-Headers的允许范围

res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With");

果然,ctrl+c,ctrl+v,解决


连接数据库

你可能感兴趣的:(express)