简体   繁体   English

无法从一台服务器到另一台服务器进行请求-“错误:请求失败,状态码为401”

[英]Uable to make a req from one server to another - “Error: Request failed with status code 401”

I am trying to make an api req from one server (localhost:3000) to another server(localhost:3001) but I am getting authentication error 401. 我正在尝试从一台服务器(localhost:3000)到另一台服务器(localhost:3001)进行api req,但是我收到身份验证错误401。

Note:If I hard code the authentication token, I am able to make the request.This let me conclude that I am not setting up the axios authentication header in a right way. 注意:如果我对身份验证令牌进行了硬编码,则可以发出请求。这使我得出结论,我没有以正确的方式设置axios身份验证标头。

apiFile.ts file apiFile.ts文件

import axios, { AxiosInstance } from 'axios';
import { Dispatch } from 'redux';
import { handleResponse } from './handlers';
import { getDiscussionsAction } from '../../redux/actions/dataActions';

  let axiosInstance: AxiosInstance = axios.create();

function addDiscussion(data:String) {
    axiosInstance.post('http://localhost:3001/api/addDiscussion',data).then(response=> {
    console.log(response)
  }).catch(error=>{
    console.log('error on adding post',error)
  })
}

function setupAxiosInstance(token: string) {
  console.log('inside setup Axios Instance')
  console.log('token setup Axios',token)
    axiosInstance = axios.create({
        headers: {
          Authorization: 'Bearer ' + token}
    });
}
export default {
    getDiscussions,
    addDiscussion,
    setupAxiosInstance
}

Expected: When I setupAxiosInstance(String) and pass token to it, it should set the header with the token for subsequent request. 预期:当我setupAxiosInstance(String)并将令牌传递给它时,它应该为后续请求设置带有令牌的标头。

Actual: Though I can see that setupAxiosInstance(String) method have received token and but in subsequent request (ex:AddDiscussion api req), it does not have the authentication 实际:虽然我可以看到setupAxiosInstance(String)方法已收到令牌,但是在随后的请求中(例如:AddDiscussion api req),它没有身份验证

[. [ It works when I hard code the token in -'let axiosInstance: AxiosInstance = axios.create();' 当我在-'let axiosInstance:AxiosInstance = axios.create();'中对令牌进行硬编码时,它可以工作 like 喜欢

let axiosInstance: AxiosInstance = axios.create({
      headers: {
        Authorization: 'Bearer fjsdkf.sdjkfksfklsdjjksfshjdfhksndyrndbsjdjasbckcnbsdcb;efjdfnsdklncsncsln'}
  });)

And also if I do something like below, it still does not work either. 而且,如果我做下面的事情,它仍然无法正常工作。

function setupAxiosInstance(token: string) {
  console.log('inside setup Axios Instance')
  console.log('token setup Axios',token)
    axiosInstance = axios.create({
        headers: {
          Authorization: 'Bearer ya29.Gl9uB4tmH0GzYyxBOmeICZa7vsNLZXPuj2du3Q4HIBMGQzZhixXWuS5mCNSPzkCzfjYK0-XNTM0bHI_Fmist9bjYU9CdD06ZtzHPs8TCHmAQcG1dryM8u9_LtfOHiaVGzA'}
    });
}

If anyone can pointout what I am doing wrong or point me in the right direction?, that would be great. 如果有人可以指出我做错了什么,或者指出正确的方向呢?那将很棒。

Instead of reassigning the instance you can set the instance headers like this 无需重新分配实例,您可以像这样设置实例头

function setupAxiosInstance(token: string) {
  console.log('inside setup Axios Instance')
  console.log('token setup Axios',token)
  axiosInstance.defaults.headers.common.Authorization = `Bearer ${token}`;
}

In case anybody faced this same issue.I was able to resolve the issue by using LinkContainer from react-router-bootstrap in my component (One of my friend figured it out. Kudos to him.).This was not an issue with axios header authorization but how I was navigating across my react components. 如果有人遇到同样的问题。我可以通过使用组件中react-router-bootstrap中的LinkContainer解决此问题(我的一个朋友知道了。对他表示敬意。)。这与axios标头无关授权,但是我如何浏览我的React组件。

Issue: Though I could see the setupAxiosInstance(String) method have received token and but in subsequent request (ex:AddDiscussion api req), it does not have the authentication. 问题:虽然我可以看到setupAxiosInstance(String)方法已经收到令牌,但是在随后的请求中(例如:AddDiscussion api req),它没有身份验证。

Reason: Everytime I was navigating to another link using href, there was a page refresh and it was deleting the header authorization. 原因:每次我使用href导航到另一个链接时,都会刷新页面,并且正在删除标题授权。

Solution: 解:

import { LinkContainer } from 'react-router-bootstrap'

use LinkContainer for navigation 使用LinkContainer进行导航

<Nav className="mr-auto">
        <LinkContainer to="/discussion">
          <Nav.Link >Discussion</Nav.Link>
        </LinkContainer>
      </Nav>
      <LinkContainer to="/add-discussion">
        <Button variant="primary" id="ask-a-question-button">Ask a Question?</Button>
      </LinkContainer>

or use push.history 或使用push.history

<Navbar.Brand href="/home" className="Nav-link">Discussion</Navbar.Brand>
        <Nav className="mr-auto" onSelect={(selectedKey: string) => console.log('selected', selectedKey)}>
          <Nav.Link onClick={() => this.props.history.push("/home")}>
            Home
            {/* <Link to="/">Home</Link> */}
          </Nav.Link>

          <Nav.Link onClick={() => this.props.history.push("/login")}>
            Login
            {/* <Link to="/login/">Login</Link> */}
          </Nav.Link>
        </Nav>
      </Navbar>

but dnt use href to navigate 但是dnt使用href导航

<Nav className="mr-auto">
  <Nav.Link href="/Discussion">Discussion</Nav.Link>
</Nav>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Reactjs 错误:未捕获(承诺中)错误:请求失败,状态码为 401 - Reactjs error: Uncaught (in promise) Error: Request failed with status code 401 错误:React JS 中的请求失败,状态代码为 401 axios - Error: Request failed with status code 401 axios in React JS 请求失败,状态码为 401 at createError "Unauthenticated" - Request failed with status code 401 at createError "Unauthenticated" 当用户想要登录时:AXIOS 错误:[错误:请求失败,状态码 401] BAD_REQUEST - when user want to login : AXIOS ERROR: [Error: Request failed with status code 401] BAD_REQUEST 我收到错误(在 postman api 调用上)错误:请求失败,状态码为 401 - i am getting error(on postman api call) Error: Request failed with status code 401 从请求标头获取401状态代码 - Get 401 status code from request header IPFS Infura 错误无法加载资源:服务器响应状态为 401(未授权)(POST 请求) - IPFS Infura ERROR Failed to load resource: the server responded with a status of 401 (Unauthorized) (POST REQUEST) 错误:请求失败,状态码 401:在 React.js 中未授权并使用 setState 进行授权 - Error: Request failed with status code 401 : Unauthorized in React.js and using setState for Authorization 我收到 Uncaught (in promise) 错误:请求失败,状态码为 401 - I am getting Uncaught (in promise) Error: Request failed with status code 401 请求失败,状态码为 401 - React 单元测试 - Request failed with status code 401 - React Unit-Testing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM