CORS错误,但仅在POST请求时有效,尽管配置了cors(GET没问题) [英] CORS error but only on POST request, despite cors config (GET have no issue)

查看:127
本文介绍了CORS错误,但仅在POST请求时有效,尽管配置了cors(GET没问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个nodejs express服务器.尽管允许主持人,但我仍然遇到CORS错误

I use a nodejs express server. Despite allowing the host, I still have an CORS error

请求中没有'Access-Control-Allow-Origin'标头资源."

" No 'Access-Control-Allow-Origin' header is present on the requested resource."

,但仅适用于POST端点."GET"没有问题.我的客户端浏览器都允许使用(GET和POST)端点:

but only for the POST endpoint. The "GET" have no issue. Both (GET and POST) endpoint are allowed for my client-browser:

我的服务器:(在 http://serverURL 上运行)

My server:(running on 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):(在localhost:4200上运行)

The client ( angular 9) : (running on localhost: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");
  }

知道为什么它不起作用吗?

any idea why it's don't work?

GET的整个请求/响应:

The whole request/response of the 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的整个响应/请求响应:

The whole response/request for the (failing) POST Response:

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

推荐答案

尝试启用针对您的路线的CORS飞行前(OPTIONS)处理.

当您需要路由来处理所谓的 complex CORS操作时,必须添加一个OPTIONS路由处理程序.浏览器发送一个额外的请求,一个OPTIONS请求.

When you need your route to handle so-called complex CORS operations, you must add a OPTIONS route handler. The browsers send an extra request, an OPTIONS request.

为什么这样复杂?因为网络蠕变.

Why is this extra complex? Because cybercreeps.

添加此路由处理程序.就在您进行帖子处理之前,是个不错的选择.

Add this route handler. Right before your post handling is a good place for it.

router.options('/score', cors())

这篇关于CORS错误,但仅在POST请求时有效,尽管配置了cors(GET没问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆