Nodejs如何解決跨域(CORS)
Nodejs解決跨域(CORS)
前后端分離的大環(huán)境下,受制于同源策略,我們需要懂得實(shí)現(xiàn)CORS(Cross-Origin Resource Sharing)
手動(dòng)配置
在nodejs中,req 和 res 參數(shù)在中間件間都指向同一對(duì)象,這樣我們就可以在頭中間件中修改res 的header。如下:
const express = require('express')
?
const app = express();
?
app.use((req, res) => {
? ? //在這里手動(dòng)配置
? ? res.header('Access-Control-Allow-Origin', 'example.com');
})CORS模塊
我們也可以通過引入cors模塊快速配置。
npm i cors --save ? //不是node的內(nèi)置模塊,需要先下載
const express = require('express')
const cors = require('cors')
?
const app = express();
?
const corsConfig = {
? origin:'http://localhost:8080',
? credentials:true,
}
//使用默認(rèn)
app.use(cors())
//或修改默認(rèn)配置
app.use(cors(corsConfig))?axios
值得注意的一點(diǎn)是cors模塊會(huì)將 Access-Control-Allow-Origin 默認(rèn)配為 *,但是axios不接受通配符*。而且axios還需要 Access-Control-Allow-Credentials 屬性為true。
Credentials我們可以手動(dòng)配置,Access-Control-Allow-Origin 我們可以如下配置 :
const express = require('express')
const cors = require('cors')
?
const app = express();
?
//使用默認(rèn)
app.use(cors())
? ?.use((req, res, next) => {
? ? ? ? console.log(req);
? ? ? ? res.setHeader('Access-Control-Allow-Origin',req.origin),
? ? ? ? next()
? ? })
//req.origin是網(wǎng)關(guān)地址 如:http://192.168.1.1?注意:本地調(diào)試的時(shí)候axios不認(rèn)為 localhost:8080 等于127.0.0.1:8080
Nodejs CORS跨域問題
在響應(yīng)頭里設(shè)置:'Access-Control-Allow-Origin': '*'
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>cors</title>
</head>
<body>
<script>
// 請(qǐng)求地址
fetch('http://localhost:3000/api/data')
// 請(qǐng)求體解析
.then(res => res.json())
// 獲得數(shù)據(jù)
.then(result => console.log(result))
</script>
</body>
</html>
server.js
const http = require('http');
const libUrl = require('url')
http.createServer((req, res) => {
const url = libUrl.parse(req.url, true);
if (url.pathname === '/favicon.ico') return;
if (url.pathname === '/api/data') {
res.writeHead(200, {
'Content-Type': 'Application/json',
// 設(shè)置允許所有端口訪問
'Access-Control-Allow-Origin': '*'
});
let obj = {
name: '張三',
age: 20,
sex: '男'
};
res.write(JSON.stringify(obj));
}
res.end();
}).listen(3000)
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
nodejs語言實(shí)現(xiàn)驗(yàn)證碼生成功能的示例代碼
這篇文章主要介紹了nodejs語言實(shí)現(xiàn)驗(yàn)證碼生成功能的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
npm?install編譯時(shí)報(bào)"Cannot?read?properties?of?null?(r
這篇文章主要給大家介紹了關(guān)于npm?install編譯時(shí)報(bào)“Cannot?read?properties?of?null?(reading?‘pickAlgorithm‘)“錯(cuò)誤的解決辦法,文中將解決方法介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
nodejs進(jìn)階(6)—連接MySQL數(shù)據(jù)庫示例
本篇文章主要介紹了nodejs進(jìn)階(6)—連接MySQL數(shù)據(jù)庫示例,詳細(xì)的介紹了NodeJS操作MySQL數(shù)據(jù)庫,作為應(yīng)用最為廣泛的開源數(shù)據(jù)庫則成為我們的首選,有興趣的可以了解一下。2017-01-01
node koa2實(shí)現(xiàn)上傳圖片并且同步上傳到七牛云存儲(chǔ)
這篇文章主要介紹了node koa2實(shí)現(xiàn)上傳圖片并且同步上傳到七牛云存儲(chǔ),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07

