Node跨域问题

Posted zhizou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node跨域问题相关的知识,希望对你有一定的参考价值。

const express = require(express),
    app = express(),
    router = express.Router(),
    bodyParser = require(body-parser); // 解析请求的body中的内容[必须]

router.all(*, function(req, res, next) { // ‘*‘代表所有的访问者都能访问
    res.header("X-Powered-By", 3.2.1)
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

    res.header(Access-Control-Allow-Methods, PUT, POST, GET, DELETE, OPTIONS);
    res.header(Access-Control-Allow-Headers, Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild);
    next();
});

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

app.use(express.static(public));
app.use(/api, router);//访问每个接口前边都需要加上(api/)(eg:http://localhost:3000/api/students)

app.listen(3000, 
    () => console.log(Example app listening on port 3000!));

router.post(/students, function(req, res, next){
    var data = req.body;
    console.log(data);
    res.json({ 
        status:1,
        data:{
            user: post
        },
    });
});

router.get(/students, function(req, res, next){
    var data = req.query;
    console.log(data);
    res.json({ 
        status:1,
        data:{
            user: get
        },
    });
});

 

以上是关于Node跨域问题的主要内容,如果未能解决你的问题,请参考以下文章

node学习-2:Cors解决跨域问题

node学习-2:Cors解决跨域问题

node学习-2:Cors解决跨域问题

Node.js+Express框架跨域解决方案

node跨域cors模块,nodejs+express跨域

带有预检的 Node.JS 中的跨域 POST 请求?