获取请求不工作
Fetch Request Not Working
我正在尝试使用 Fetch API or request 将自定义 header、X-Query-Key
添加到 HTTP 请求,但是当我将其添加到请求的 header 时由于某种原因,header 设置似乎失败,Request Method
设置为 OPTIONS
。
当我删除 header 时,它会恢复到应有的 GET
。
示例代码如下所示:
const options = {
url: url,
headers: {
'Accept': 'application/json',
'X-Query-Key': '123456' //Adding this breaks the request
}
};
return request(options, (err, res, body) => {
console.log(body);
});
试试这个:
const headers = new Headers({
"Accept": "application/json",
"X-Query-Key": "123456",
});
const options = {
url: url,
headers: headers
};
return request(options, (err, res, body) => {
console.log(body);
});
如果这不能解决问题,可能与 CORS.
有关
Custom headers on cross-origin requests must be supported by the
server from which the resource is requested. The server in this
example would need to be configured to accept the X-Custom-Header
header in order for the fetch to succeed. When a custom header is set,
the browser performs a preflight check. This means that the browser
first sends an OPTIONS request to the server to determine what HTTP
methods and headers are allowed by the server. If the server is
configured to accept the method and headers of the original request,
then it is sent. Otherwise, an error is thrown.
因此,如果使用自定义 headers,您将有 2 个请求,第一个使用方法 OPTIONS 来检查服务器是否允许自定义 headers,然后是服务器响应是否为 200 OK 并允许您的原始请求请求第二个将被发送
我正在尝试使用 Fetch API or request 将自定义 header、X-Query-Key
添加到 HTTP 请求,但是当我将其添加到请求的 header 时由于某种原因,header 设置似乎失败,Request Method
设置为 OPTIONS
。
当我删除 header 时,它会恢复到应有的 GET
。
示例代码如下所示:
const options = {
url: url,
headers: {
'Accept': 'application/json',
'X-Query-Key': '123456' //Adding this breaks the request
}
};
return request(options, (err, res, body) => {
console.log(body);
});
试试这个:
const headers = new Headers({
"Accept": "application/json",
"X-Query-Key": "123456",
});
const options = {
url: url,
headers: headers
};
return request(options, (err, res, body) => {
console.log(body);
});
如果这不能解决问题,可能与 CORS.
有关Custom headers on cross-origin requests must be supported by the server from which the resource is requested. The server in this example would need to be configured to accept the X-Custom-Header header in order for the fetch to succeed. When a custom header is set, the browser performs a preflight check. This means that the browser first sends an OPTIONS request to the server to determine what HTTP methods and headers are allowed by the server. If the server is configured to accept the method and headers of the original request, then it is sent. Otherwise, an error is thrown.
因此,如果使用自定义 headers,您将有 2 个请求,第一个使用方法 OPTIONS 来检查服务器是否允许自定义 headers,然后是服务器响应是否为 200 OK 并允许您的原始请求请求第二个将被发送