我使用Node.js的Express服务器。
尽管已经允许了主机,但仍然出现了CORS错误。
我的服务器:(运行在http://serverURL上)
客户端(Angular 9):(运行在本地主机:4200端口)。
任何想法为什么它不起作用?
整个GET请求/响应:
响应:
整个(失败的)POST请求/响应 响应:
但仅限于POST端点。GET端点没有问题。 我的客户端浏览器都允许使用(GET和POST)端点。"请求资源中没有'Access-Control-Allow-Origin'标头。"
我的服务器:(运行在http://serverURL上)
var whitelist = ['http://localhost:4200', 'http://someOtherDeployUrl.com']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = {origin: true} // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = {origin: false} // disable CORS for this request
}
corsOptions.methods= "GET,HEAD,PUT,PATCH,POST,DELETE";
callback(null, corsOptions) // callback expects two parameters: error and options
}
router.post('/score', cors(corsOptionsDelegate), function (req, res, next) {
...
res.status(200).send('Ok');
});
router.get('/scores', cors(corsOptionsDelegate), function (req, res, next) {
res.status(200).send(scores);
});
客户端(Angular 9):(运行在本地主机:4200端口)。
public saveScore(player, score) {
console.log("save score")
let objectObservable = this.http.post("http://serverURL/score", {
player: player,
score
}).subscribe(
data => console.log('success', data),
error => console.log('oops', error)
);
return objectObservable
}
public getScores() {
return this.http.get("http://serverURL/scores");
}
任何想法为什么它不起作用?
整个GET请求/响应:
响应:
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: http://localhost:4200
Content-Length: 2
Content-Type: application/json; charset=utf-8
Date: Sun, 14 Jun 2020 14:42:35 GMT
Etag: W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Server: Cowboy
Vary: Origin
Via: 1.1 vegur
X-Powered-By: Express
请求:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.9,fr-FR;q=0.8,fr;q=0.7
Connection: keep-alive
DNT: 1
Host: serverUrl
If-None-Match: W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Origin: http://localhost:4200
Referer: http://localhost:4200/menu
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
整个(失败的)POST请求/响应 响应:
Allow: POST
Connection: keep-alive
Content-Length: 4
Content-Type: text/html; charset=utf-8
Date: Sun, 14 Jun 2020 14:30:00 GMT
Etag: W/"4-Yf+Bwwqjx254r+pisuO9HfpJ6FQ"
Server: Cowboy
Via: 1.1 vegur
X-Powered-By: Express
请求:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.9,fr-FR;q=0.8,fr;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: serverUrl
Origin: http://localhost:4200
Referer: http://localhost:4200/menu
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36