从使用Fetch进行的POST请求的响应头中获取日期。

huangapple go评论77阅读模式
英文:

Get date from response headers in a POST request using Fetch

问题

我正在尝试从响应头中获取日期,但只返回了Content-Type。是否可能获取日期?

在进行POST请求后,以下是我的响应头:

从使用Fetch进行的POST请求的响应头中获取日期。

以下是我用于进行POST请求的实用函数:

export default async function postData(url, func, audience, requestObj) {
	const accessToken = await func({
		audience: audience,
	});

	const myHeaders = new Headers();

	myHeaders.append('authorization', `Bearer ${accessToken}`);
	myHeaders.append('Content-Type', 'application/json');

	const raw = JSON.stringify(requestObj);

	const requestOptions = {
		method: 'POST',
		headers: myHeaders,
		body: raw,
		redirect: 'follow',
	};

	const response = await fetch(url, requestOptions);
    const transactionDate = response.headers.get('Date');

    //This returns null
    console.log('Date', transactionDate);

    //This returns only the Content-Type
	for (let pair of response.headers.entries()) {
		console.log(pair[0] + ': ' + pair[1]);
	}
	if (!response.ok) {
		if (response.status >= 500 && response.status <= 599) {
			throw new Error(
				'A server error occurred and we were unable to submit your data.'
			);
		} else if (response.status >= 400 && response.status <= 499) {
			const text = await response.text();
			throw new Error(text);
		} else {
			throw new Error(`${response.status}: ${response.statusText}`);
		}
	}

	const result = await response.json();
	return result;
}
英文:

UPDATED

I am trying to get the Date from my response headers but only Content-Type is returned. Is it possible to get the date?

Here are my response headers after making a POST request:

从使用Fetch进行的POST请求的响应头中获取日期。

Here is my utility function for making the POST request:

export default async function postData(url, func, audience, requestObj) {
const accessToken = await func({
audience: audience,
});
const myHeaders = new Headers();
myHeaders.append(&#39;authorization&#39;, `Bearer ${accessToken}`);
myHeaders.append(&#39;Content-Type&#39;, &#39;application/json&#39;);
const raw = JSON.stringify(requestObj);
const requestOptions = {
method: &#39;POST&#39;,
headers: myHeaders,
body: raw,
redirect: &#39;follow&#39;,
};
const response = await fetch(url, requestOptions);
const transactionDate = response.headers.get(&#39;Date&#39;);
//This returns null
console.log(&#39;Date&#39;, transactionDate);
//This returns only the Content-Type
for (let pair of response.headers.entries()) {
console.log(pair[0] + &#39;: &#39; + pair[1]);
}
if (!response.ok) {
if (response.status &gt;= 500 &amp;&amp; response.status &lt;= 599) {
throw new Error(
&#39;A server error occurred and we were unable to submit your data.&#39;
);
} else if (response.status &gt;= 400 &amp;&amp; response.status &lt;= 499) {
const text = await response.text();
throw new Error(text);
} else {
throw new Error(`${response.status}: ${response.statusText}`);
}
}
const result = await response.json();
return result;
}

答案1

得分: 0

这是 postData 的结束部分:

const result = await response.json();
return result;

它不会返回响应。它会将响应体解析为 JSON 并返回结果数据结构。

该数据结构不包括标头。它们存在于 response 对象中。

如果你想在 postData 之外获取该数据,那么你需要在那里读取该值 (response.headers) 并返回它(可能作为一个包括 result 值的数组或对象的一部分)。

英文:

This is the end of postData:

> const result = await response.json();
> return result;

It doesn't return the response. It parses the response body as JSON and returns the resulting data structure.

That data structure doesn't include the headers. They exist on the response object.

If you want that data outside of postData then you'll need to read that value (response.headers) there and return it (possibly as part of an array or object that also includes the value of result).

答案2

得分: 0

正如评论中指出的,响应头中的 Date 是一个 禁止使用的头名称(https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name),不能被访问。

您可以使用 Access-Control-Expose-Headers(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers)来暴露 Date,或者如果担心使用 Access-Control-Expose-Headers,您可以返回一个包含日期信息的自定义 HTTP 头部。

英文:

As was pointed out in the comments, Date in the response header is a Forbidden Header Name (https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) and cannot be accessed.

You can use Access-Control-Expose-Headers (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers) to expose the Date or if there is a concern about using Access-Control-Expose-Headers you can return a custom HTTP header with the date information instead.

huangapple
  • 本文由 发表于 2023年7月12日 22:46:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定