[英]Express server has CORS enabled, though it still fails when performing aync HTTP request from Angular
這是我們目前遇到的一些奇怪問題,我們需要有關此問題的幫助。
首先,我們有一個Express服務器,該服務器可提供一些數據,充當API,並且在從同一個域使用時可以很好地工作。 沒問題
但是我們也想從計算機上使用此API(因為它在開發服務器中),以利用數據並更輕松,更快速地進行測試。 這不是一個怪異的方法,對嗎? 好了,那么我們只需在Express文件中設置CORS。 這是我們的API:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const fs = require("fs");
const MockupData = require('./MockupData').MockupData;
// Setting up CORS and bodyparser
app.use(bodyParser.json());
app.use( (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.static('public'));
// Mockup data setter
let mockupData;
const assignCollection = (requestedCollection) => {
if(!mockupData || mockupData.collection != requestedCollection){
mockupData = new MockupData(requestedCollection, false);
}
}
const errorHandler = (err, res) => {
console.error("ERR: ", err);
res.status(500);
res.render('error', { error: err });
}
// Router
app.post("/api", (req, res) => {
res.setHeader('Content-Type', 'application/json');
assignCollection("achieved_combined");
if(mockupData){
mockupData.get(req.body)
.then(data => res.send(data))
.catch(err => errorHandler(err, res));
}else{
errorHandler(err, res);
}
});
app.get("/", (req, res) => {
res.send("API responding");
})
app.listen(80, () => console.log("Pseudo-server listening to port 80"));
從Angular,這是調用:
@Injectable()
export class DataRequester{
url = "http://our.subdomain.com";
constructor(private http:Http){
}
/**
* This method receives the "config" stateful object for setting up the
* conditions of the data that the app needs from the server. The data is
* returned in a promise that is fulfilled when the data is ready to be
* consumed.
* @param config The config object with all the data.
* @param reportTypes Types of reports to fetch. Options: cross_section, timeseries, panel
* @returns The backend's response for the stated conditions.
*/
requestData(config, reportTypes){
return new Promise( (resolve, reject) => {
const query = this.buildQuery(config, reportTypes);
this.http.post(this.url+"/api", query).subscribe( (response:any) => {
if(response._body){
const data = JSON.parse(response._body);
console.log(data)
resolve(data);
}
}, err => this.errorHandler(err, reject));
})
}
但是,它總是不斷給出相同的錯誤:
跨域請求被阻止:“相同源策略”不允許讀取http://webdev.objectiveportal.com/api上的遠程資源。 (原因:CORS標頭“ Access-Control-Allow-Origin”缺失)。
為什么會失敗? 您是否知道為什么會這樣?
我們將非常感謝您的幫助! 謝謝!
嘗試使用Express / CORS中間件。 首先npm install cors --save-prod
: npm install cors --save-prod
然后,要啟用從所有來源進行的訪問,無需手動設置標題。 只需將以下內容添加到服務器的代碼中:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
有關更多詳細信息,請參見https://github.com/expressjs/cors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.