沃梦达 / 编程问答 / php问题 / 正文

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

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]

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

本文标题为:带有正确标头的预检响应不成功

基础教程推荐