NodeJS跨域问题

一、使用cors中间件解决跨域(推荐)

var cors = require("cors"); //  cnpm install cors

app.use(cors({
  methods: ["GET", "POST"],
  alloweHeaders: ["Content-Type", "application/json;charset=utf-8;application/x-www-form-urlencoded"]
}));

 

二、传统的方式解决跨域问题

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'
        },
    });
});

 

 

 

 

 

  

 

转载于:https://www.cnblogs.com/zhizou/p/10495013.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值