我正在嘗試將資料從 angular(埠 4200)發布到埠 3000 上的后端 node.js express 服務器。
到目前為止我所做的:我嘗試將 json 資料從 angular 發布到 httpbin.org(用于測驗使用的第 3 方服務器),這證明我在 angular 中的函式對于發布 json 資料是有效的。
另外,我使用 angular 從其他網站的 API 獲取資料,并且它們都可以作業,只有托管在埠 3000 上的 nodejs 服務器在從 angular 向其發布資料時出現 CORS 問題。
我一直在使用谷歌搜索更改 nodejs 服務器的 cors 標頭,并檢查了防火墻和許多其他方法,但沒有任何效果,我總是收到 CORS 錯誤。
**Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:3000/api/postData. (Reason: CORS request did not succeed).**
**ERROR:**
Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:3000/api/postData", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://127.0.0.1:3000/api/postData: 0 Unknown Error", error: error }
?
error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
?
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
?
message: "Http failure response for http://127.0.0.1:3000/api/postData: 0 Unknown Error"
?
name: "HttpErrorResponse"
?
ok: false
?
status: 0
?
statusText: "Unknown Error"
?
url: "http://127.0.0.1:3000/api/postData"
?
<prototype>: Object { … }
Angular 檔案:compoent.ts
getData(loc : any) {
//angular --> nodejs
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http.post<any>("http://127.0.0.1:3000/api/postData", JSON.stringify(loc)).subscribe(response =>{
console.log(response);
});
I tried all kinds of headers and cors that I can find on the internet in this Nodejs file but nothing works: app.js
const express = require('express')
const app = express()
const port = 3000
const cors = require('cors')
app.options('*', cors()) // include before other routes
//app.use(cors())
const corsOpts = {
origin: '127.0.0.1:3000',
methods: [
'GET',
'POST',
],
allowedHeaders: [
'Content-Type',
],
};
app.use(cors(corsOpts));
app.use(function(req, res, next) {
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// next();
// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', '127.0.0.1:3000');
// Request methods you wish to allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'Accept, Content-Type, X-Requested-With', 'X-HTTP-Method-Override');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.header('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
app.use(
cors({
allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
exposedHeaders: ["authorization"], // you can change the headers
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false
})
);
app.get('/', (req, res, next) => {
res.send("wtffffffffffffffffff");//send to the page
})
app.get('/getAPIResponse', (req, res, next) => {
api_helper.make_API_call('https://jsonplaceholder.typicode.com/posts')
.then(response => {
res.json(response)
})
.catch(error => {
res.send(error)
})
})
//angular --> nodejs
app.post('/api/postData',cors(), (req, res, next) => {
console.log("/postData success when running ng serve");
console.log(req.body);
})
app.listen(port, () => console.log(`NodeJS App listening on port ${port}!`))
This is the proxy file : proxy.conf.json
{
"/api/*": {
"target": "http://127.0.0.1:3000",
"pathRewrite": {"^/api" : ""},
"secure" : false,
"changeOrigin" : true
}
}
uj5u.com熱心網友回復:
從檔案
簡單使用(啟用所有 CORS 請求)
const express = require('express')
const cors = require('cors')
const 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')
})
首先讓基本的 CORS 設定作業,然后考慮使用一些 CORS 配置來敲打艙口。
如果您使用 CORS,還要洗掉您的代理配置。如果使用 CORS,則直接從 FE(瀏覽器)向您的 BE 服務器發出 HTTP 請求。
uj5u.com熱心網友回復:
問題很簡單:我沒有在后端運行nodejs服務器
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349607.html
標籤:node.js angular express cors cross-domain
