我的带有React,Express,MongoDB的应用程序。
我想为Axios发布请求传递带有标头的身份验证令牌。
但是,当我尝试通过它时,出现403错误(禁止)。
本地存储
在这里,我正在从本地存储中检索所有身份验证数据
strsql = "SELECT * FROM TblJob WHERE JobID=" & Me.JobID
Axios.post
在这里,我正在致电axios发布请求
export function authHeader() {
// return authorization header with basic auth credentials
let user = JSON.parse(localStorage.getItem('user'));
if (user && user.token) {
return { Authorization: `Bearer ${user.token}` };
} else {
return {};
}
}
API标头和响应
这是我从浏览器中得到的响应
import React, { Component } from 'react'
import Axios from 'axios';
import { authHeader } from '../../../helpers'
export default class SubAdmin extends Component {
constructor(props) {
super(props)
this.state = {
user: {},
users: [],
error: null,
isLoaded: false,
items: []
}
};
componentDidMount() {
this.setState({
user: JSON.parse(localStorage.getItem('user')),
users: { loading: true }
});
Axios.post('http://localhost:4200/api/viewSubAdmin',
{
headers: authHeader()
}).then(
result => {
console.log(result);
this.setState({
isLoaded: true,
items: result.data
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
我的邮递员通话正常
Request URL: http://localhost:4200/api/viewSubAdmin
Request Method: POST
Status Code: 403 Forbidden
Remote Address: [::1]:4200
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 9
Content-Type: text/plain; charset=utf-8
Date: Mon, 23 Mar 2020 10:04:33 GMT
ETag: W/"9-PatfYBLj4Um1qTm5zrukoLhNyPU"
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 171
Content-Type: application/json;charset=UTF-8
Host: localhost:4200
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
{headers: {,…}}
headers: {,…}
Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6IjEyMzQ1Njc4OSIsImlhdCI6MTU4NDk1MDM3MH0.Bk4q3qEsVrA8TDn7Bbk5M689B-6uVfg4r9FTmfDTWc4"
答案 0 :(得分:1)
Axios.post
依次接收url
,data
和headers
作为参数。如果您仅通过url
和headers
,则必须以null
的身份通过data
axios.post(url, null, headers)
或者您可以尝试Axios api
Axios({
method: 'post',
url: 'http://localhost:4200/api/viewSubAdmin',
headers: authHeader()
}).then.....
答案 1 :(得分:0)
您的代码中有一些错误,我已经修改了您的代码。请使用以下代码替换您的axios呼叫并检查
Axios.post('http://localhost:4200/api/viewSubAdmin',{
headers: authHeader()
}).then(result => {
console.log(result)
this.setState({
isLoaded: true,
items: result.data
})
}).catch(error => {
this.setState({
isLoaded: true,
error
})
});