Fetch响应中缺少标头

时间:2018-01-24 00:29:31

标签: javascript fetch axios

我需要制作CORS post request。我需要使用fetch,因为axios' s 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));

5 个答案:

答案 0 :(得分:15)

fetch返回的Headers类实例是iterable,而不是像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));

答案 1 :(得分:2)

要获取特定的标头属性,可以使用以下命令:

response.headers.get(yourProperty)

答案 2 :(得分:2)

标头仅限于CORS请求。参见https://stackoverflow.com/a/44816592/2047472

(使用import com.sun.javafx.PlatformUtil; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Test; import org.openqa.selenium.support.PageFactory; public class HotelBookingTest { WebDriver driver; @FindBy(xpath= "//*[@class='hotelApp ']") public static WebElement hotelLink; @Test public void shouldBeAbleToSearchForHotels() { setDriverPath(); driver = new ChromeDriver(); HotelBookingTest.setPageObject(driver); driver.get("https://www.cleartrip.com/"); boolean hotelLinkDisplayed = hotelLink.isDisplayed(); hotelLink.click(); driver.quit(); } public static void setPageObject (WebDriver wd) { PageFactory.initElements(wd, new HotelBookingTest ()); } } 可以将标头暴露给来自其他来源的请求。)

答案 3 :(得分:0)

尽管正确的答案是@AndyTheEntity的答案,但对我来说还是有点不完整。

CORS请求具有局限性,并且仅显示标头的一部分:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

为了在响应中显示更多标题,服务器必须添加标题以允许更多标题。

例如,在POST请求之后,如果创建了新资源,则应返回201 CREATED响应并添加一个Location标头。 如果您需要接受CORS,还需要添加下一个标头(在 server 响应上):

Location: $url-of-created-resource
Access-Control-Expose-Headers: Location

有了它,您将在客户端上看到标题Location

如果您需要发送特定的标头(例如SESSION_ID),则需要在请求中添加下一个标头:

Access-Control-Request-Headers: SESSION_ID
SESSION_ID: $current_session_id

我希望本文涵盖了使用CORS处理请求/响应的所有需求。

答案 4 :(得分:0)

另一种选择是使用 Object.fromEntries(),例如 Object.fromEntries(response.headers)Object.fromEntries(response.headers.entries())。此方法将键值对列表转换为对象。

fetch("https://www.google.com").then(response => console.log(Object.fromEntries(response.headers)))
//-> Promise <pending>

// console.log output:
{
    "alt-svc": "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"",
    "bfcache-opt-in": "unload",
    "cache-control": "private, max-age=0",
    "content-encoding": "br",
    "content-length": "41556",
    "content-security-policy": "upgrade-insecure-requests",
    "content-type": "text/html; charset=UTF-8",
    "date": "Wed, 04 Aug 2021 08:09:30 GMT",
    "expires": "-1",
    "server": "gws",
    "strict-transport-security": "max-age=31536000",
    "x-frame-options": "SAMEORIGIN",
    "x-xss-protection": "0"
}

注意: Internet Explorer 和 Opera Android 目前不支持此功能,请参阅 browser compatibility on MDN docs

相关问题