正确的标头,预检响应不成功 [英] Preflight response is not successful with proper headers

查看:91
本文介绍了正确的标头,预检响应不成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将离子应用程序发布到API时遇到问题。在我的api上,我设置了以下标头:

I'm having issue getting my ionic app to POST to my API. On my api I have set the following headers:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS");

从Postman或实际网站上发布时,所有功能均按预期运行,我看到这些标头又回来了,但一旦我打开我的应用并发送请求,它就不再起作用。

When posting from Postman or the actual website, everything functions as expected and I see these headers come back but once I open up my app and send a request, it no longer works.

GET请求工作正常,只是POST请求被破坏了。我使用以下命令在我的应用上发送发布请求:

GET Requests are working fine, it's just POST requests that are broken. I use the following to send a post request on my app:

 /**
  * Post to the API
  * @param path    Where to go
  * @param params  What to send
  */
 private post(path, params): Promise<any> {
   return this.http
     .post(this.apiUrl + path, params)
     .toPromise()
     .then(r => r.json());
 }

我在离子应用程序内部遇到以下错误

I get the following error inside of my ionic app

Failed to load resource: Preflight response is not successful
XMLHttpRequest cannot load https://mmcalc.com/api/calculate. Preflight response is not successful

我已经为此花了将近15个小时,我不明白为什么它不起作用。

I've been pulling my hair out over this for nearly 15 hours now, I don't understand why it won't work.

推荐答案

解决方案非常简单,但不是很明显,我只需要在API上设置适当的标头即可。 这篇文章为我解决了这个问题,非常简单。

The solution was very simple but not very obvious, I simply had to set the proper headers on my API. This article solved the issue for me and was very simple.

# Always set these headers.
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

# Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

这篇关于正确的标头,预检响应不成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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