我想向外部 API 发出 HTTP Post 请求,但是当我尝试从 React 使用 axios 执行此操作时,出现 CORS 错误(请求的资源上不存在“Access-Control-Allow-Origin”标头)。同时,在 .NET 中提出此请求时,一切似乎都没问题。我不知道为什么它会这样工作,所以也许有人可以弄清楚。
反应请求:
var bodyFormData = new FormData();
bodyFormData.append('key', 'apiKey');
bodyFormData.append('function', 'getTeams');
async function fetchData() {
await axios({
url: 'https://external.api/api/',
method: 'POST',
data: bodyFormData,
withCredentials: true,
headers: {
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
})
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log(err)
});
}
fetchData();
.NET 请求:
var request = (HttpWebRequest)WebRequest.Create("https://external.api/api/");
var postData = "key=apiKey";
postData += "&function=getTeams";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
CORS 是一种仅适用于客户端(浏览器)的安全措施。Origin
无论您是否需要,浏览器都会发送标头,API 会检查标头以决定它是否应该为您服务(通过允许浏览器继续处理主要请求)。
您可以毫无问题地从后端发送请求,因为没有Origin
标题可言。
所以你有两个选择:
https://$domain:$port
。如果 API 在您的控制之下,这应该很容易,否则,代理是一个更直接的解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句