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

 

 

 

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM