为什么我的JavaScript代码会接收A; no访问conscess-control-allow-origin'标题存在于请求的资源上。错误,虽然邮递员没有?

发布于 2025-01-24 04:31:13 字数 1757 浏览 3 评论 0 原文

mod注释:这个问题是关于 xmlhttprequest / fetch /etc的原因。在浏览器上,在邮递员不遵守相同的访问策略限制(您会遇到CORB或CORS的错误)。这个问题是而不是关于如何修复“ no'''访问控制 - 允许 - 原始'...”错误。这是关于为什么发生的原因。

请停止发布


我试图使用 JavaScript 通过连接到“ noreferrer”> //en.wikipedia.org/wiki/application_programming_interface“ rel =“ noreferrer”> api =“ noreferrer”>烧瓶。但是,当我提出请求时,我会收到以下错误:

XMLHttpRequest cannot load http://myApiUrl/login. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'null' is therefore not allowed access.

我知道API或远程资源必须设置标头,但是当我通过Chrome Extension postman

这是请求代码:

$.ajax({
  type: 'POST',
  dataType: 'text',
  url: api,
  username: 'user',
  password: 'pass',
  crossDomain: true,
  xhrFields: {
    withCredentials: true,
  },
})
  .done(function (data) {
    console.log('done');
  })
  .fail(function (xhr, textStatus, errorThrown) {
    alert(xhr.responseText);
    alert(textStatus);
  });

Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.

Please stop posting:

  • CORS configurations for every language/framework under the sun. Instead find your relevant language/framework's question.
  • 3rd party services that allow a request to circumvent CORS
  • Command line options for turning off CORS for various browsers

I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:

XMLHttpRequest cannot load http://myApiUrl/login. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'null' is therefore not allowed access.

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?

This is the request code:

$.ajax({
  type: 'POST',
  dataType: 'text',
  url: api,
  username: 'user',
  password: 'pass',
  crossDomain: true,
  xhrFields: {
    withCredentials: true,
  },
})
  .done(function (data) {
    console.log('done');
  })
  .fail(function (xhr, textStatus, errorThrown) {
    alert(xhr.responseText);
    alert(textStatus);
  });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

一指流沙 2025-01-31 04:31:13

如果我理解的是,您正在做一个 xmlhttprequest 到与您的页面不同的域。因此,出于安全原因,浏览器通常会阻止它,因为它通常允许以相同的来源为单位。当您想执行跨域请求时,您需要做一些不同的事情。

当您使用Postman时,他们不受此政策的限制。引用 cross-origin xmlhtttprequest

常规网页可以使用xmlhttprequest对象从远程服务器发送和接收数据,但它们受相同的原始策略的限制。扩展不受限制。只要它首先请求交叉原始权限,扩展程序就可以与远程服务器交谈。

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request.

When you are using Postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

泼猴你往哪里跑 2025-01-31 04:31:13

警告:使用 access-control-allow-Origin: *可以使您的API/网站易受跨站点请求伪造(CSRF)攻击。确保您了解风险在使用此代码之前。

如果您使用的是 php 非常简单。只需在PHP页面的开头中添加以下脚本来处理请求:

<?php header('Access-Control-Allow-Origin: *'); ?>

如果您使用您必须允许 cors settings.js 文件通过删除以下几行:

// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
  origin: "*",
  methods: "GET,PUT,POST,DELETE"
},

如果使用 flask 问题;您首先要安装烧结仪

pip install -U flask-cors

然后在您的应用程序中包含烧瓶 cors 软件包。

from flask_cors import CORS

一个简单的应用程序将看起来像:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

有关更多详细信息,您可以检查“ noreferrer”> flask document

WARNING: Using Access-Control-Allow-Origin: * can make your API/website vulnerable to cross-site request forgery (CSRF) attacks. Make certain you understand the risks before using this code.

It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:

<?php header('Access-Control-Allow-Origin: *'); ?>

If you are using Node-red you have to allow CORS in the node-red/settings.js file by un-commenting the following lines:

// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
  origin: "*",
  methods: "GET,PUT,POST,DELETE"
},

If you are using Flask same as the question; you have first to install flask-cors

pip install -U flask-cors

Then include the Flask cors package in your application.

from flask_cors import CORS

A simple application will look like:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

For more details, you can check the Flask documentation.

揪着可爱 2025-01-31 04:31:13

因为
$。ajax({type:“ post” - 调用 options
$。post( - 调用 post

都不同。 Postman < /a>正确调用“发布”,但是当我们调用它时,它将是“选项”

。 #apache_license_2.0_release“ rel =“ noreferrer”> web api

请在您的 web.config 文件中添加以下代码。将工作:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

中没有犯任何错误。

请确保您在jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);
    },
    error: function () {
        console.log("error");
    }
});

>这将无法帮助您

System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");

Because
$.ajax({type: "POST" - calls OPTIONS
$.post( - calls POST

Both are different. Postman calls "POST" properly, but when we call it, it will be "OPTIONS".

For C# web services - Web API

Please add the following code in your web.config file under the <system.webServer> tag. This will work:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

Please make sure you are not doing any mistake in the Ajax call.

jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);
    },
    error: function () {
        console.log("error");
    }
});

Note: If you are looking for downloading content from a third-party website then this will not help you. You can try the following code, but not JavaScript.

System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
芸娘子的小脾气 2025-01-31 04:31:13

以下调查中为API,我使用 http://example.com 而不是http:// myapiurl/login您的问题,因为第一个工作。我认为您的页面在 http://my-site.local.local:8088

注意:API和您的页面具有不同的域!

您看到不同结果的原因是Postman:

  • set header host = example.com (您的api)
  • 未设置标题 onect> onement
  • Postman实际上根本不使用您的网站URL(您仅在Postman中键入API地址) - 他仅发送请求到API,因此他假设网站的地址与API相同(浏览器不假定此),

这与浏览器的网站和API具有浏览器的方式相似相同的域(浏览器还设置标题项目 Referer = http://my-site.local:8088 ,但是我在Postman中看不到它)。 Origin 标题是不是设置时,通常服务器默认允许此类请求。

这是邮递员的标准方式发送请求。但是,当您的网站和API具有不同的域,然后 cors 发生并且浏览器会自动:

  • sets header host = host = example.com (您作为api)
  • 设置header oince> oincount site.local:8088 (您的网站)

(标题 Referer 具有与 origin 的值相同的值。现在在Chrome的 Console&amp;网络选项卡您将看到:

”输入图像说明在此处”

”在此处输入图像描述”

当您拥有 主机!当服务器检测到此类请求时,它通常默认情况下将其阻止

Origin = null 是从本地目录打开HTML内容时设置的,并发送请求。同样的情况是,当您在&lt; iframe&gt; 中发送请求时,就像在下面的摘要中一样(但此处 host bester 完全未设置标题) - 一般而言,到处html规范上说不透明的起源,您可以将其转换为 onect = null 。有关此的更多信息,您可以找到在这里

fetch('http://example.com/api', {method: 'POST'});
Look on chrome-console > network tab

如果您不使用简单的CORS请求,则通常浏览器在发送主请求之前会自动发送选项请求 - 更多信息是在这里。下面的摘要显示了:

fetch('http://example.com/api', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json'}
});
Look in chrome-console -> network tab to 'api' request.
This is the OPTIONS request (the server does not allow sending a POST request)

您可以更改服务器的配置以允许CORS请求。

这是一个示例配置,该配置在nginx (nginx.conf文件)上打开 cors-在设置时要非常小心 ewern/'$ http_origin“ for nginx and nginx and >” *“ for apache-这将解开任何域(在生产而不是星星中使用您的混凝土页面adres),以消耗您的API)

location ~ ^/index\.php(/|$) {
   ...
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    if ($request_method = OPTIONS) {
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        return 204;
    }
}

这是一个示例配置

# ------------------------------------------------------------------------------
# | Cross-domain Ajax requests                                                 |
# ------------------------------------------------------------------------------

# Enable cross-origin Ajax requests.
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
# http://enable-cors.org/

# <IfModule mod_headers.c>
#    Header set Access-Control-Allow-Origin "*"
# </IfModule>

# Header set Header set Access-Control-Allow-Origin "*"
# Header always set Access-Control-Allow-Credentials "true"

Access-Control-Allow-Origin "http://your-page.com:80"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"

Deep

In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working. I assume that your page is on http://my-site.local:8088.

NOTE: The API and your page have different domains!

The reason why you see different results is that Postman:

  • set header Host=example.com (your API)
  • NOT set header Origin
  • Postman actually not use your website url at all (you only type your API address into Postman) - he only send request to API, so he assume that website has same address as API (browser not assume this)

This is similar to browsers' way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088, however I don't see it in Postman). When Origin header is not set, usually servers allow such requests by default.

Enter image description here

This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:

  • sets header Host=example.com (yours as API)
  • sets header Origin=http://my-site.local:8088 (your site)

(The header Referer has the same value as Origin). And now in Chrome's Console & Networks tab you will see:

Enter image description here

Enter image description here

When you have Host != Origin this is CORS, and when the server detects such a request, it usually blocks it by default.

Origin=null is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>, like in the below snippet (but here the Host header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null. More information about this you can find here.

fetch('http://example.com/api', {method: 'POST'});
Look on chrome-console > network tab

If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request - more information is here. The snippet below shows it:

fetch('http://example.com/api', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json'}
});
Look in chrome-console -> network tab to 'api' request.
This is the OPTIONS request (the server does not allow sending a POST request)

You can change the configuration of your server to allow CORS requests.

Here is an example configuration which turns on CORS on nginx (nginx.conf file) - be very careful with setting always/"$http_origin" for nginx and "*" for Apache - this will unblock CORS from any domain (in production instead of stars use your concrete page adres which consume your api)

location ~ ^/index\.php(/|$) {
   ...
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    if ($request_method = OPTIONS) {
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        return 204;
    }
}

Here is an example configuration which turns on CORS on Apache (.htaccess file)

# ------------------------------------------------------------------------------
# | Cross-domain Ajax requests                                                 |
# ------------------------------------------------------------------------------

# Enable cross-origin Ajax requests.
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
# http://enable-cors.org/

# <IfModule mod_headers.c>
#    Header set Access-Control-Allow-Origin "*"
# </IfModule>

# Header set Header set Access-Control-Allow-Origin "*"
# Header always set Access-Control-Allow-Credentials "true"

Access-Control-Allow-Origin "http://your-page.com:80"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"

鸢与 2025-01-31 04:31:13

应用CORS限制是服务器定义并由浏览器实现的安全功能。

浏览器查看服务器的CORS策略并尊重它。

但是,Postman工具不会打扰服务器的CORS策略。

这就是为什么CORS错误出现在浏览器中但不在Postman中的原因。

Applying a CORS restriction is a security feature defined by a server and implemented by a browser.

The browser looks at the CORS policy of the server and respects it.

However, the Postman tool does not bother about the CORS policy of the server.

That is why the CORS error appears in the browser, but not in Postman.

奈何桥上唱咆哮 2025-01-31 04:31:13

您获得的错误是由于CORS标准造成的,该标准对JavaScript如何执行Ajax请求设定了一些限制。

CORS标准是在浏览器中实现的客户端标准。因此,是浏览器阻止调用完成并生成错误消息 - 而不是服务器。

Postman并未实施CORS限制,这就是为什么您在邮递员进行相同电话时看不到相同的错误的原因。

为什么 postman不实施CORS? COR定义了相对于启动请求的页面的原点(URL域)的限制。但是在Postman中,请求并非来自带有URL的页面,因此CORS不适用。

The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests.

The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.

Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.

Why doesn't Postman implement CORS? CORS defines the restrictions relative to the origin (URL domain) of the page which initiates the request. But in Postman the requests doesn't originate from a page with an URL so CORS does not apply.

镜花水月 2025-01-31 04:31:13

解决方案&amp;问题起源

您正在制作 xmlhtttprequest

  1. 域一个: some-domain.com
  2. 域二: different-domain.com

域名触发的这种差异触发 cors =“ https://developer.mozilla.org/en-us/docs/web/http/cors” rel =“ noreferrer”> Cross-Origin Resources共享)称为 sop ) ( same-origin Policy ) (因此, Origin )在 ajax ,xmlhtttprequest

当我通过Chrome扩展程序提出请求时,为什么它可以工作
邮递员?

客户(大多数浏览器开发工具)可以选择执行相同的原始政策。

大多数浏览器都执行相同原产政策的政策,以防止与 csrf 相关的问题(跨站点请求伪造)攻击。

Postman 作为开发工具选择不强制执行SOP,而某些浏览器执行,这就是为什么您的原因可以通过Postman发送请求,您无法使用浏览器通过JS与XMLHTTPRequest发送。

Solution & Issue Origins

You are making a XMLHttpRequest to different domains, example:

  1. Domain one: some-domain.com
  2. Domain Two: some-different-domain.com

This difference in domain names triggers CORS (Cross-Origin Resource Sharing) policy called SOP (Same-Origin Policy) that enforces the use of same domains (hence Origin) in Ajax, XMLHttpRequest and other HTTP requests.

Why did it work when I made the request via the Chrome extension
Postman?

A client (most Browsers and Development Tools) has a choice to enforce the Same-Origin Policy.

Most browsers enforce the policy of Same-Origin Policy to prevent issues related to CSRF (Cross-Site Request Forgery) attack.

Postman as a development tool chooses not to enforce SOP while some browsers enforce, this is why you can send requests via Postman that you cannot send with XMLHttpRequest via JS using the browser.

心凉 2025-01-31 04:31:13

为了浏览器测试目的:

Windows-运行:

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

上面的命令将禁用Chrome Web安全性。因此,例如,如果您在尝试提出请求时在本地项目上工作并遇到CORS策略问题,则可以使用上述命令跳过此类型的错误。基本上,它将开启新的Chrome会议。

For browser testing purposes:

Windows - Run:

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

The command above will disable chrome web security. So for example if you work on a local project and encounter CORS policy issue when trying to make a request, you can skip this type of error with the above command. Basically it will open a new chrome session.

萌无敌 2025-01-31 04:31:13

如果您的网关超时太短,并且您要访问的资源要比超时所需的时间更长的资源,您也可能会遇到此错误。复杂数据库查询等可能是这种情况。因此,上述错误代码可以掩盖此问题。只需检查错误代码是否为504而不是404允许原素 - i/59353387#59353387“> kamil的答案或其他东西。如果是504,则增加门户超时可能会解决问题。

在我的情况下,可以通过在浏览器,请参见 如何禁用同一来源的互联网Explorer 。执行此操作后,这是日志中纯​​504误差。

You might also get this error if your gateway timeout is too short and the resource you are accessing takes longer to process than the timeout. This may be the case for complex database queries etc. Thus, the above error code can be disguishing this problem. Just check if the error code is 504 instead of 404 as in Kamil's answer or something else. If it is 504, then increasing the gateway timeout might fix the problem.

In my case the CORS error could be removed by disabling the same origin policy (CORS) in the Internet Explorer browser, see How to disable same origin policy Internet Explorer. After doing this, it was a pure 504 error in the log.

李不 2025-01-31 04:31:13

) dopost()函数中写入此代码行

要解决此问题,请在您的 doget ( control-allow-origin“,”*”);

而不是“*” 您可以在网站或API URL端点键入访问网站的API URL端点,否则将是公开的。

To resolve this issue, write this line of code in your doGet() or doPost() function whichever you are using in backend

response.setHeader("Access-Control-Allow-Origin", "*");

Instead of "*" you can type in the website or API URL endpoint which is accessing the website else it will be public.

勿忘心安 2025-01-31 04:31:13

您的IP地址未列出您的IP地址,因此您会遇到此错误。
要求后端员工为您要访问的服务白色IP地址。

Your IP address is not whitelisted, so you are getting this error.
Ask the backend staff to whitelist your IP address for the service you are accessing.

Access-Control-Allow-Headers

庆幸我还是我 2025-01-31 04:31:13

对我而言,我出于不同的原因而遇到了这个问题,远程域被添加到起源中,部署的应用程序正常工作,除了一个终点,我得到了这个问题:

Origin https://mai-frontend.vercel.app is not allowed by Access-Control-Allow-Origin. Status code: 500

Fetch API cannot load https://sciigo.herokuapp.com/recommendations/recommendationsByUser/8f1bb29e-8ce6-4df2-b138-ffe53650dbab due to access control checks.

发现我的Heroku数据库表不包含我本地表的所有列的所有列更新Heroku数据库表,一切都很好。

For me I got this issue for different reason, the remote domain was added to origins the deployed app works perfectly except one end point I got this issue:

Origin https://mai-frontend.vercel.app is not allowed by Access-Control-Allow-Origin. Status code: 500

and

Fetch API cannot load https://sciigo.herokuapp.com/recommendations/recommendationsByUser/8f1bb29e-8ce6-4df2-b138-ffe53650dbab due to access control checks.

I discovered that my Heroku database table does not contains all the columns of my local table after updating Heroku database table everything worked well.

风透绣罗衣 2025-01-31 04:31:13

您可以通过在服务器中的 web.config 文件中添加以下脚本来允许 cors

<system.webServer>
     <httpProtocol>
         <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="*" />
            <add name="Access-Control-Allow-Headers" value="*" />
         </customHeaders>
     </httpProtocol>
</system.webServer>

You can allow the CORS by adding below scripts in web.config file in server.

<system.webServer>
     <httpProtocol>
         <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="*" />
            <add name="Access-Control-Allow-Headers" value="*" />
         </customHeaders>
     </httpProtocol>
</system.webServer>
千紇 2025-01-31 04:31:13

这可能会帮助参考: /tomcat-9.0-doc/images/cors-flowchart.png 从链接参考文档复制粘贴图像。

CORS流程图

This may help ref: https://tomcat.apache.org/tomcat-9.0-doc/images/cors-flowchart.png Copy pasting image from the link reference documentation.

CORS Flow Chart
enter image description here

錯遇了你 2025-01-31 04:31:13

对我来说,我只是更改了浏览器,然后它起作用了。我当时在Localhost上工作。我的API在Localhost上:7133,我的应用在Localhost:5173。在Chrome and Edge中,它不起作用,但是当我尝试使用Opera尝试时,它就起作用了。我认为,当我在不同域上发布API和Web应用程序时,这将是一个解决方案。

For me, I just changed the browser, then it worked. I was working on localhost. My API was on localhost:7133 and my app was on localhost:5173. In Chrome and Edge, it didn't work, but when I tried it with Opera, it worked. I think when I publish the API and web app on different domains, it will be a solution.

涙—继续流 2025-01-31 04:31:13

我们的问题被触发了我的 modSecurity 在Nginx上。所请求的从未到达PHP服务器,并将403返回Google Chrome;而且,由于我们有两个不同的域(原点和目的地)Chrome了解到缺乏访问控制 - 允许 - Origin 是一个问题。

该解决方案是将请求编码为base64或更新nginx上的modSecurity设置,以不再阻止请求。

Our issue was triggered my ModSecurity on nginx. The requested never got to the PHP server and returned 403 to Google Chrome; and since we had two different domains (origin and destination) Chrome understood that the lack of Access-Control-Allow-Origin was a CORS issue.

The solution is to encode the request as base64 or update your ModSecurity settings on nginx to no longer block the request.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文