在 NodeJS 应用程序中发出 HTTP 请求时何时显式设置 headers
When to set the headers explicitly when making HTTP request in NodeJS application
所以我查看了 NodeJS 应用程序的代码库,发现有一些特定的函数向后端发出 HTTP 请求。确切地说,这些函数正在向后端发出 GET 请求,我发现令人困惑的一件事是,在某些函数中, headers 被明确提及,而在其他一些发出 GET 请求的函数中, 没有提到 headers (即 headers 没有被明确设置)。下面是一个例子:
在下面的代码中,该函数正在发出 GET 请求并且没有提及 headers(即未明确设置 headers):
// Method for fetching a single post from the backend on the basis of the post ID
export const singlePost = (postID) => {
return fetch(http://localhost:8080/post/${postID}, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((error) => {
console.log(error);
});
};
在下面的代码中,函数正在发出 GET 请求并且 headers 被显式设置:
// Helper Method for making the call to the backend and fetching all their details of all the posts
export const list = (page) => {
return fetch(http://localhost:8080/posts/?page=${page}, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
return response.json();
})
.catch((error) => console.log(error));
};
现在来到主要问题,有人可以向我解释一下我们什么时候应该明确设置 headers 不仅在 GET 请求中而且在其他一般 HTTP 请求中也是如此(即 POST、放置、选项等)。
如果有人可以在此处引用来源或解释这个概念,那就太好了。谢谢!
HTTP 请求 header 是用户浏览器发送到 Web 服务器的文本记录形式的信息,其中包含浏览器想要的内容的详细信息以及将从服务器接受的内容。请求 header 还包含发出请求的浏览器的类型、版本和功能,以便服务器 returns 兼容数据。
检查这个 https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039
所以我查看了 NodeJS 应用程序的代码库,发现有一些特定的函数向后端发出 HTTP 请求。确切地说,这些函数正在向后端发出 GET 请求,我发现令人困惑的一件事是,在某些函数中, headers 被明确提及,而在其他一些发出 GET 请求的函数中, 没有提到 headers (即 headers 没有被明确设置)。下面是一个例子:
在下面的代码中,该函数正在发出 GET 请求并且没有提及 headers(即未明确设置 headers):
// Method for fetching a single post from the backend on the basis of the post ID
export const singlePost = (postID) => {
return fetch(http://localhost:8080/post/${postID}, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((error) => {
console.log(error);
});
};
在下面的代码中,函数正在发出 GET 请求并且 headers 被显式设置:
// Helper Method for making the call to the backend and fetching all their details of all the posts
export const list = (page) => {
return fetch(http://localhost:8080/posts/?page=${page}, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
return response.json();
})
.catch((error) => console.log(error));
};
现在来到主要问题,有人可以向我解释一下我们什么时候应该明确设置 headers 不仅在 GET 请求中而且在其他一般 HTTP 请求中也是如此(即 POST、放置、选项等)。
如果有人可以在此处引用来源或解释这个概念,那就太好了。谢谢!
HTTP 请求 header 是用户浏览器发送到 Web 服务器的文本记录形式的信息,其中包含浏览器想要的内容的详细信息以及将从服务器接受的内容。请求 header 还包含发出请求的浏览器的类型、版本和功能,以便服务器 returns 兼容数据。 检查这个 https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039