【问题标题】:Making ajax request in javascript when cors is not allowed from serverside?当服务器端不允许 cors 时在 javascript 中发出 ajax 请求?
【发布时间】:2018-08-20 15:30:46
【问题描述】:
  • 使用 Fetch 请求

function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(new Error(response.statusText))
  }
}

function json(response) {
  return response.json()
}


fetch('https://apis.mapmyindia.com/advancedmaps/v1/+apikey+/autosuggest?q=delhi',{mode: 'no-cors'})
  .then(status)
  .then(json)
  .then(function(data) {
    console.log('Request succeeded with JSON response', data);
  }).catch(function(error) {
    console.log('Request failed', error);
  });

以上代码报错

我也尝试过使用 httprequest,但它不起作用

【问题讨论】:

  • “但它不起作用” - 是的,那是因为它不应该 ...您需要通过您自己的服务器代理此请求(因此从客户端的角度来看,它不再是跨域的),或者添加适当 CORS 标头的第 3 方服务器。
  • +apikey+ 是描述中的错误还是您的代码中的错误?
  • @CBroe 如果我没有服务器访问权限,那么如何发出请求
  • No @SamGhatak apikey 不是错误

标签: javascript ajax cors


【解决方案1】:

它不起作用,因为您必须在服务器上启用 cors。但是,您可以为此使用代理服务器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-20
    • 2020-04-09
    • 2020-03-19
    • 2020-09-26
    • 2023-03-10
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多