首页 > 解决方案 > 当服务器端不允许 cors 时在 javascript 中发出 ajax 请求?

问题描述

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,但它不起作用

标签: javascriptajaxcors

解决方案


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


推荐阅读