node.js搭建介面(九):Node-使用中介軟體實現跨域
阿新 • • 發佈:2019-01-06
使用中介軟體進行跨域必須寫在使用路由之前
//使用中介軟體實現跨域請求
app.use((req,res,next) => {
res.header("Access-Control-Allow-Origin","*"); //允許的來源
res.header("Access-Control-Allow-Headers","Content-Type"); //請求的頭部
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); //允許請求的方法
next();
})
也可以使用cors 進行跨域
首先需要安裝cors
npm install cors
隨後在入口檔案中引入並使用
var express = require('express') var cors = require('cors') var app = express() app.use(cors()) app.get('/products/:id', function (req, res, next) { res.json({msg: 'This is CORS-enabled for all origins!'}) }) app.listen(80, function () { console.log('CORS-enabled web server listening on port 80') })