这是我们现在遇到的一些奇怪的问题,我们需要一些关于这个问题的帮助。
首先,我们有一个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 标头"访问控制允许源")。
为什么会失败?你知道为什么会这样吗?
我们真的很感激一些帮助!谢谢!
尝试使用 Express/CORS 中间件。首先安装它:npm install cors --save-prod
然后,要启用来自所有源的访问,无需手动设置标头。只需将以下内容添加到服务器代码中:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
有关更多详细信息,请参阅 https://github.com/expressjs/cors