【问题标题】:Need a way to enable CORS in vueJS [duplicate]需要一种在 vueJS 中启用 CORS 的方法 [重复]
【发布时间】:2020-10-08 02:49:51
【问题描述】:

我是 vueJS 的新手,使用的版本是 2.0。我需要从 url 获取一些 JSON 数据。使用 javacsript fetch 方法从 URL 获取数据。下面是我的代码,

function getValue() {
            const requestOptions = {
                method: "GET",
                header: {"Access-Control-Allow-Origin": "GET"}
            };
              fetch("http://api.plos.org/search?q=title:DNA", requestOptions)
                .then(
                    (response) => {
                        console.log(response.json());
                    }
                );
        }

        getValue();

我遇到了类似的 CORS 问题,

Access to fetch at 'http://api.plos.org/search?q=title:DNA' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我尝试了堆栈溢出中可用的所有可能性。但没有运气。 任何帮助将非常感激。 JSFiddle 链接 - https://jsfiddle.net/m45hsekf/

【问题讨论】:

  • CORS 应该在服务器级别启用,例如节点或 java 应用程序。

标签: javascript vuejs2


【解决方案1】:

CORS 应该在服务器级别启用,例如节点或 java 应用程序。

Access-Control-Allow-Origin : "test-client.com" or use "*"(不推荐)。然后在服务器上允许这个值

Get 是你的 http 方法而不是原始值

要在节点中启用,请使用此行

res. header("Access-Control-Allow-Origin", "*"); // again * is not a best practice. Please accept this as answer too

有关更多信息,请参阅下面的网址 https://dzone.com/articles/cors-in-node

【讨论】:

【解决方案2】:

您是否尝试像错误提示的那样将模式设置为no-cors

将请求的模式设置为“no-cors”以使用 CORS 获取资源 已禁用。

我已经测试过了,它可以工作:

const requestOptions = {
      method: "GET",
      mode: "no-cors"
};

所以请求看起来像这样:

fetch("http://api.plos.org/search?q=title:DNA", {
  mode: "no-cors"
})
  .then(response => response.json())
  .then(result => {
    console.log(result);
  });

【讨论】:

  • 试过这个,并在response.json() 中得到类似Uncaught (in promise) SyntaxError: Unexpected end of input 的错误。不知道是什么原因
【解决方案3】:

当我在开发过程中遇到问题时,我使用名为 CORS UNBLOCK 的 crhome 扩展,然后我可以测试我的 api,当我部署到最终服务器时,总是在同一个域中,然后我没有 cors ploblem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2011-02-21
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多