为什么在运行GET请求onChange时仅遇到CORS错误?

时间:2019-06-08 23:25:32

标签: javascript node.js reactjs here-api

我正在使用在proxy: "localhost:5000中设置package.json的Create-React-App Client,以便在Node.js服务器上轻松查询API。

我正在尝试通过以下功能使用HERE的自动完成API。

自动完成功能:

import axios from 'axios';
import hereKeys from '../config/hereConfig';

export const autoCompleteFullAddress = async query => {
  let address = null;
  try {
    await axios
      .get('https://autocomplete.geocoder.api.here.com/6.2/suggest.json', {
        params: {
          app_id: hereKeys.appId,
          app_code: hereKeys.appCode,
          query: query,
          maxresults: 1,
        },
      })
      .then(response => {
        address = response.data.suggestions[0].address;
      });
  } finally {
    return address;
  }
};

我在正在渲染的组件中有一个辅助函数,可以根据用户对输入字段的输入来执行此功能。

输入组件:

 const [puAddress, setPuAddress] = useState('');
 const [puQuery, setPuQuery] = useState('');

  const onAddressInput = e => {
    const query = e.target.value;

// This Fails
    autoCompleteFullAddress(query).then(suggestion => {
      setPuQuery(query);
      console.log(suggestion);
    });
  };

// This works
  autoCompleteFullAddress('37044 Even Lane').then(suggestion => {
    console.log(suggestion);
  });

return (
  <TextField
     value={puQuery}
     onChange={e => onAddressInput(e)}
  />
);

autoCompleteFullAddress单独运行时,console.log是正确的输出。但是一旦我尝试在组件的更改上执行此操作,它就会失败并引发错误。

引发错误:

Access to XMLHttpRequest at 'https://autocomplete.geocoder.api.here.com/6.2/suggest.json?
app_id=REDACTED&app_code=REDACTED&query=Elm+St&maxresults=1' 
from origin 'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
It does not have HTTP ok status.

并且:

OPTIONS https://autocomplete.geocoder.api.here.com/6.2/suggest.json?
app_id=REDACTED&app_code=REDACTED&query=Elm+St&maxresults=1 405

失败的请求标头:

Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Referer: http://localhost:3000/pricing-tool
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36

成功的请求标题:

Accept: application/json, text/plain, */*
Origin: http://localhost:3000
Referer: http://localhost:3000/pricing-tool
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36

1 个答案:

答案 0 :(得分:0)

对于将来可能会设置访问令牌以便向您的API发出请求的人们。问题是它试图在所有Axios请求上发送带有令牌的Auth头。

import axios from 'axios';

const setAuthToken = token => {
  if (token) {
    const bearerToken = 'Bearer ' + token;
    // Apply to every request
    axios.defaults.headers.common['Authorization'] = bearerToken;
  } else {
    // Delete auth header
    delete axios.defaults.headers.common['Authorization'];
  }
};

export default setAuthToken;

可以通过更改逻辑来解决,也可以简单地对外部API使用访存。

我已固定删除该特定请求的标头。

import axios from 'axios';
import hereKeys from '../config/hereConfig';

export const autoCompleteFullAddress = async query => {
  let address = null;
  delete axios.defaults.headers.common['Authorization'];
  try {
    await axios
      .get('https://autocomplete.geocoder.api.here.com/6.2/suggest.json', {
        crossdomain: true,
        params: {
          app_id: hereKeys.appId,
          app_code: hereKeys.appCode,
          query: query,
          maxresults: 1,
          country: 'USA,MEX,CAN',
        },
      })
      .then(response => {
        address = response.data.suggestions[0].address;
      });
  } finally {
    return address;
  }
};