带有正确标头的预检响应不成功

Preflight response is not successful with proper headers(带有正确标头的预检响应不成功)
本文介绍了带有正确标头的预检响应不成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将我的 ionic 应用程序发布到我的 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());
 }

我的 ionic 应用程序中出现以下错误

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]

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)