码迷,mamicode.com
首页 > 其他好文 > 详细

Node跨域问题

时间:2019-03-08 12:43:16      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:expr   parse   class   ted   let   log   lis   end   www   

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跨域问题

标签:expr   parse   class   ted   let   log   lis   end   www   

原文地址:https://www.cnblogs.com/zhizou/p/10495013.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!