React JS 应用程序中的我的组件不读取 REST-Api 中的标头 - 标头为空

问题描述 投票:0回答:1

我使用 C# 创建了一个使用 React.Js 和 Asp.Net core 构建的 Web 应用程序。

当我从

Postman
Swagger
发出请求时,我会收到来自响应的
headers
。 来自招摇:

Request and Response from Swagger

对于邮递员来说也是同样的结果。

在 React.js 中,我使用以下代码调用我的端点:

const res = await fetch(url, options);
const data = await res.json();
console.log("Head " ,res);

我的

console.log
在应用程序中检查是(标题为空): enter image description here

我确实使用授权选项获取端点,但

Response
有空标头。为什么??

来自带有路径的库

node_modules\typescript\lib\lib.dom.d.ts\fetch
还有我的获取: enter image description here

我的程序.json

{
  "name": "linkedin",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "start": "vite preview",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "build": "vite build --watch"
  },
  "dependencies": {
    "@cloudinary/react": "^1.13.0",
    "@cloudinary/url-gen": "^1.20.0",
    "@fortawesome/fontawesome-free": "^6.6.0",
    "@fortawesome/fontawesome-svg-core": "^6.6.0",
    "@fortawesome/free-solid-svg-icons": "^6.6.0",
    "@fortawesome/react-fontawesome": "^0.2.2",
    "@react-icons/all-files": "^4.1.0",
    "axios": "^1.6.8",
    "cloudinary": "^2.4.0",
    "cors": "^2.8.5",
    "express": "^4.19.2",
    "mssql": "^10.0.2",
    "multer": "^1.4.5-lts.1",
    "path": "^0.12.7",
    "primeicons": "^7.0.0",
    "primereact": "^10.8.2",
    "react": "^18.2.0",
    "react-datepicker": "^7.3.0",
    "react-dom": "^18.2.0",
    "react-icons": "^5.1.0",
    "react-router-dom": "^6.23.1",
    "watch": "^0.13.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@vitejs/plugin-react": "^4.2.1",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.6",
    "vite": "^5.4.0",
    "webpack-dev-server": "^5.0.4"
  }
}

你有办法解决我的问题吗?

javascript reactjs rest http-headers fetch
1个回答
0
投票

它不为空,您需要使用

get
函数来检索所需的标头或使用
forEach
遍历所有标头

const res = await fetch(url, options);
const exampleHeader = res.headers.get('Content-Type');
console.log("exampleHeader ", exampleHeader);
res.headers.forEach((value, key) => {
  console.log(`${key} ==> ${value}`);
});
const data = await res.json();
console.log("Head " ,res);

了解更多信息https://developer.mozilla.org/en-US/docs/Web/API/Headers/get

© www.soinside.com 2019 - 2024. All rights reserved.