无法从前端JavaScript访问跨域响应标头 [英] Can’t access cross-origin response header from frontend JavaScript

查看:51
本文介绍了无法从前端JavaScript访问跨域响应标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ReactJS create-react-app 构建一个简单的Web应用。

I am building a simple web app using ReactJS and create-react-app.

我有在Heroku上设置的后端API,我可以在其中发出 POST 请求。一切正常,除了:

I have a backend API set up on Heroku where I can make POST requests. Everything works fine, except:

当我使用访存API发出POST请求时,响应为100%正确,但仅提供2个标准标头。我想获取自定义标题。我在响应中添加了暴露标题,这是情节的转折:当我从Chrome Inspection Tool或Postman(API工具)查看标题时,它会显示所有标题,包括我的自定义标题。我正在使用的提取代码-

When I make a POST request using fetch API, the response is 100% correct but it only gives me 2 standard headers. I want to get my custom header. I have added expose header in my response and here's the plot twist: When I view the headers from Chrome Inspection Tool or Postman (API tool), it shows all the headers, including my custom one. Here is the fetch code I'm using -

fetch(theUrl, {
  method: 'POST',
  body: JSON.stringify({
    "placeholder": "placeholder"
  })
})
.then(function(res) {
  console.log(res.headers.get('CUSTOM_HEADER_NAME'));
})

如果有所不同,此获取方法是从ReactJS组件主体外部的函数调用的。

If it makes any difference, this fetch method is called from a function outside the main body of the ReactJS component.

自定义标头的名称为 Image -Identification-Path ,而我的响应标头中的标头为 Image-Identification的 Access-Control-Expose-Headers -路径

The name of the custom header is Image-Identification-Path, and the header in my response header is Access-Control-Expose-Headers for Image-Identification-Path.

摘要:如何使用访存获取自定义标头?

推荐答案

您必须配置将请求发送到的服务器,以便其响应具有 Access-Control-Expose-Headers

You must configure the server to which the request is sent, such that its response has an Access-Control-Expose-Headers header whose value has the name of your custom response header.

否则,如果您的浏览器在 Access-中看不到您的自定义标题的名称, Control-Expose-Headers 标头,它不允许您访问自定义响应标头的值。

Otherwise, if your browser doesn’t see the name of your custom header in that Access-Control-Expose-Headers header, it won’t let you access the value of your custom response header.

在这种情况下,预计您会如果您在Postman甚至浏览器devtools中查看响应,仍然能够看到自定义标头。

In such a case it’s expected that you’d still be able to see the custom header if you look at the response in Postman or even in your browser devtools.

但是仅仅因为浏览器在响应中获得了自定义标头并不意味着浏览器会将其公开给您的前端JavaScript代码。

But just because the browser gets the custom header in the response doesn’t mean the browser will expose it to your frontend JavaScript code.

对于跨域请求,仅当该标头名称为 Access-Control-Expose-Headers 标头。

For cross-origin requests, browsers will only expose that custom response header to your frontend code if that header name is in the value of the Access-Control-Expose-Headers header.

这篇关于无法从前端JavaScript访问跨域响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆