简体   繁体   English

避免在Rest API中使用CORS

[英]Avoid CORS in rest API

I'm having a problem to make a call to a rest API. 我在调用rest API时遇到问题。

In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Web应用程序的文档(FAQ)中有一个使用AJAX请求进行调用的示例。 Here an example: 这里是一个例子:

var url = 'https://example.com/yyy';

$.ajax({
    type: 'POST',
    url: url,
    cache: false,
    data: {
        opt: JSON.stringify(example)
    },
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (result)
    {
        console.log(result);
    } });

I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS. 我使用此代码创建了本地页面,以将其发布到位于远程服务器上的API,但收到有关CORS的错误。

Is there any solution to circumvent this problem? 有什么解决办法可以避免这个问题? I tried to use firefox plugin to allow CORS but it didn't solve the problem. 我试图使用firefox插件来允许CORS,但是它不能解决问题。 The session is authenticated via form before use the endpoint. 在使用端点之前,将通过表单对会话进行身份验证。

I see several issues: 我看到几个问题:

  1. Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ ) 尝试从域而不是从本地磁盘运行代码(或者,您可以考虑使用https://crossorigin.me/
  2. How does the authentication work? 身份验证如何工作? if with cookies you need to add withCredentials to the ajax request. 如果使用cookie,则需要将withCredentials添加到ajax请求中。
  3. Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true 确保API返回Access-Control-Allow-Origin: foo标头,其中foo是代码在其中运行的域。如果还Access-Control-Allow-Credentials: true使用,则应添加Access-Control-Allow-Credentials: true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM