wil*_*iam 4 javascript fetch axios
我需要做一个CORS post request.我需要使用fetch,因为axios的response已加工成JSON.
但作为fetch回应,这headers是空的.但我不认为这是服务器问题,因为axios响应头具有我想要的值.
任何诡计?
fetch('http://localhost:9876/test/sample-download', {
method: 'post',
headers: {},
body: {}
})
.then(response => {
console.log(response);
})
.catch(err => console.error(err));
axios.post('http://localhost:9876/test/sample-download', {}, {})
.then(response => console.log(response))
.catch(error => console.error(error));
Run Code Online (Sandbox Code Playgroud)
ccn*_*kes 29
fetch返回的Headers类实例是一个可迭代的,而不是像axios返回的普通对象.某些可迭代的数据(如Headers或URLSearchParams)无法从控制台查看,您必须迭代它并控制每个元素的console.log,如:
fetch('http://localhost:9876/test/sample-download', {
method: 'post',
headers: {},
body: {}
})
.then(response => {
// Inspect the headers in the response
response.headers.forEach(console.log);
// OR you can do this
for(let entry of response.headers.entries()) {
console.log(entry);
}
})
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
Car*_*des 20
虽然正确答案是@AndyTheEntity 对我来说有点不完整。
CORS 请求有限制,仅显示标头的子集:
Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma为了在响应中显示更多标头,服务器必须添加一个标头以允许更多额外标头。
例如,在创建新资源的 POST 请求之后,您应该返回 201 CREATED 响应并添加Location标头。如果您还需要接受 CORS,您还需要添加下一个标头(在服务器响应中):
Location: $url-of-created-resource
Access-Control-Expose-Headers: Location
Run Code Online (Sandbox Code Playgroud)
有了这个,您将在客户端上看到标题Location。
如果您需要发送特定标头(如 a SESSION_ID),则需要在请求中添加下一个标头:
Access-Control-Request-Headers: SESSION_ID
SESSION_ID: $current_session_id
Run Code Online (Sandbox Code Playgroud)
我希望这涵盖了使用 CORS 处理请求/响应的所有需求。
标头仅限于CORS请求。参见/sf/answers/3137161471/
(access-control-expose-headers用于允许将标头暴露给来自其他来源的请求。)
小智 8
要获取特定的标题属性,您可以使用以下内容:
response.headers.get(yourProperty)
Run Code Online (Sandbox Code Playgroud)