使用 Netlify 部署时调用 API 失败,在本地服务时工作正常(Reactjs 网站)
Calling an API fails when deployed with Netlify, works fine when served locally (Reactjs website)
我正在构建一个 React js 网站,我必须在其中调用货币转换器 API。
调用 API 在本地(在本地主机上)服务时完美运行,但是一旦我将其部署到 Netlify,它就无法工作。
ConvertCurrency = async (from, to, amount) => {
let endpoint = 'xxxxxx';
let access_key = "xxxxxxxxxxxx";
const url = 'http://data.fixer.io/api/' + endpoint + '?access_key=' + access_key + '&from=' + from + '&to=' + to + '&amount=' + amount;
try {
const res = await Axios.get(url)
const rate = Math.round(((res.data.info.rate* 100) / 100)).toFixed(2)
return rate;
} catch (err) {
console.log(err)
}
return -1;
}
这是我捕获的错误(在 try{}catch(){} 异常中)。
Error: Network Error
at e.exports (createError.js:17)
at XMLHttpRequest.p.onerror (xhr.js:83)
感谢任何帮助。
谢谢
我发现错误了!
解决方案:
问题是使用 HTTP 而不是 HTTPS。这是因为要让 API 在生产环境中满足您的请求,您需要提供安全的 URL.
const url = 'https://data.fixer.io/api/' + endpoint + '?access_key=' + access_key + '&from=' + from + '&to=' + to + '&amount=' + amount;
我正在构建一个 React js 网站,我必须在其中调用货币转换器 API。 调用 API 在本地(在本地主机上)服务时完美运行,但是一旦我将其部署到 Netlify,它就无法工作。
ConvertCurrency = async (from, to, amount) => {
let endpoint = 'xxxxxx';
let access_key = "xxxxxxxxxxxx";
const url = 'http://data.fixer.io/api/' + endpoint + '?access_key=' + access_key + '&from=' + from + '&to=' + to + '&amount=' + amount;
try {
const res = await Axios.get(url)
const rate = Math.round(((res.data.info.rate* 100) / 100)).toFixed(2)
return rate;
} catch (err) {
console.log(err)
}
return -1;
}
这是我捕获的错误(在 try{}catch(){} 异常中)。
Error: Network Error
at e.exports (createError.js:17)
at XMLHttpRequest.p.onerror (xhr.js:83)
感谢任何帮助。
谢谢
我发现错误了!
解决方案:
问题是使用 HTTP 而不是 HTTPS。这是因为要让 API 在生产环境中满足您的请求,您需要提供安全的 URL.
const url = 'https://data.fixer.io/api/' + endpoint + '?access_key=' + access_key + '&from=' + from + '&to=' + to + '&amount=' + amount;