【问题标题】:Problem when request News API with Java Script fetch command run command from the google chrome console使用 Javascript fetch 命令从 google chrome 控制台请求新闻 API 运行命令时出现问题
【发布时间】:2020-10-11 03:56:06
【问题描述】:

代码:

async function getNews() {
    const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&pageSize=1&apiKey=a876816f98574cdfa23ffdc7d531c7bc');
    const jsonResp = await response.json();
    return jsonResp;
}

n = await getNews();

Google Chrome 控制台中显示的错误:

访问获取 'http://newsapi.org/v2/top-headlines?country=in&pageSize=1&apiKey=a876816f98574cdfa23ffdc7d531c7bc' 来自原点 'chrome-search://local-ntp' 已被 CORS 阻止 政策:没有“Access-Control-Allow-Origin”标头出现在 请求的资源。如果不透明的响应满足您的需求,请将 请求模式为“no-cors”以获取禁用 CORS 的资源。

获取http://newsapi.org/v2/top-headlines 国家/地区=in&pageSize=1&apiKey=a876816f98574cdfa23ffdc7d531c7bc net::ERR_FAILED getNews @ VM88:2(匿名)@ VM94:1

未捕获的类型错误:获取失败

link to error image

【问题讨论】:

  • 将协议从 http 改为 https 并检查,它说不允许来自浏览器的请求
  • 您似乎正在从您的开发系统中访问此 url,并且 API 可能已阻止 localhost 服务器调用。尝试通过在某些云服务器上部署来实现这一点。

标签: javascript


【解决方案1】:

CORS 通常通过在服务器端设置响应标头来修复,如下所示

 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

但暂时你可以使用 chrome CORS 插件从其他主机获取数据

【讨论】:

  • 感谢您的回复。我从哪里放了这些代码块?
  • 这必须在服务器端设置为响应头,看来您正在使用一些您没有任何控制权的第 3 方 API(newsapi.org/v2/top-headlines)。尝试安装 Allow CORS: Access-Control-Allow-Origin - Google Chrome 插件
【解决方案2】:

尝试使用https://newsapi.org 而不是http://newsapi.org 作为端点。

【讨论】:

  • 感谢您的回复。但是在将 http 替换为 https 后,我收到新错误:{status: "error", code: "corsNotAllowed", message: "Developer plan 中不允许来自浏览器的请求,除了来自 localhost。"} 代码:"corsNotAllowed " message: "开发者计划不允许来自浏览器的请求,除非来自本地主机。"状态:“错误”proto:对象
猜你喜欢
  • 2014-12-17
  • 2013-04-12
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
相关资源
最近更新 更多