在我的反应应用程序中,我使用 axios 来执行 REST api 请求。
但它无法随请求一起发送 Authorization 标头。
这是我的代码:
tokenPayload() {
let config = {
headers: {
'Authorization': 'Bearer ' + validToken()
}
}
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
config
)
.then( ( response ) => {
console.log( response )
} )
.catch()
}
这里的 validToken()
方法将简单地从浏览器存储中返回令牌。
所有请求都有一个 500 错误响应,说明
无法从请求中解析令牌
从后端。
如何在每个请求中发送授权标头?你会推荐任何其他带有反应的模块吗?
axios
问题。检查您的 validToken()
函数,它返回您的服务器不理解的东西。
const config = {
headers: { Authorization: `Bearer ${token}` }
};
const bodyParameters = {
key: "value"
};
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
bodyParameters,
config
).then(console.log).catch(console.log);
第一个参数是 URL。第二个是将随您的请求发送的 JSON 正文。第三个参数是标题(除其他外)。这也是 JSON。
这是在 axios 中设置授权令牌的一种独特方式。为每个 axios 调用设置配置不是一个好主意,您可以通过以下方式更改默认授权令牌:
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;
一些 API 要求将 bearer 写成 Bearer,所以你可以这样做:
axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
现在您不需要为每个 API 调用设置配置。现在授权令牌设置为每个 axios 调用。
Bearer
需要大写(我发现很难)。
您可以创建一次配置并在任何地方使用它。
const instance = axios.create({
baseURL: 'https://example.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
headers: {'Authorization': 'Bearer '+token}
const instance = (token) => axios.create({ baseURL: `${config.API_URL}`, timeout: 1000, headers :{ 'authorization': 'Bearer ' + token } })
axios.post
的第二个参数是 data
(不是 config
)。 config
是第三个参数。详情请参阅:https://github.com/mzabriskie/axios#axiosposturl-data-config
通过使用 Axios 拦截器:
const service = axios.create({
timeout: 20000 // request timeout
});
// request interceptor
service.interceptors.request.use(
config => {
// Do something before request is sent
config.headers["Authorization"] = "bearer " + getToken();
return config;
},
error => {
Promise.reject(error);
}
);
如果您想在标头中传递令牌后获取一些数据,请尝试此代码
const api = 'your api';
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
console.log(error)
});
这可行,我只需要在 app.js
中设置一次令牌:
axios.defaults.headers.common = {
'Authorization': 'Bearer ' + token
};
然后我可以在我的组件中发出请求,而无需再次设置标头。
"axios": "^0.19.0",
以防万一有人遇到同样的问题。
这里的问题是当传递没有数据的标头时,标头的配置将在有效负载数据中,所以我需要传递 null 而不是数据,然后设置标头的配置。
const config = {
headers: {
"Content-type": "application/json",
"Authorization": `Bearer ${Cookies.get("jwt")}`,
},
};
axios.get(`${BASE_URL}`, null, config)
我使用一个单独的文件来初始化 axios 实例,同时,我向它添加了拦截器。然后在每次调用中,拦截器都会为我将令牌添加到请求标头中。
import axios from 'axios';
import { getToken } from '../hooks/useToken';
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_BASE_URL,
});
axiosInstance.interceptors.request.use(
(config) => {
const token = getToken();
const auth = token ? `Bearer ${token}` : '';
config.headers.common['Authorization'] = auth;
return config;
},
(error) => Promise.reject(error),
);
export default axiosInstance;
这是我在服务文件中使用它的方式。
import { CancelToken } from 'axios';
import { ToolResponse } from '../types/Tool';
import axiosInstance from './axios';
export const getTools = (cancelToken: CancelToken): Promise<ToolResponse> => {
return axiosInstance.get('tool', { cancelToken });
};
// usetoken 是钩子,我疯了
export const useToken = () => {
return JSON.parse(localStorage.getItem('user')).token || ''
}
const token = useToken();
const axiosIntance = axios.create({
baseURL: api,
headers: {
'Authorization':`Bearer ${token}`
}
});
axiosIntance.interceptors.request.use((req) => {
if(token){
req.headers.Authorization = `Bearer ${token}`;
}
return req;
})
如果您发送带有空数据的发布请求,请记住始终将第二个参数设置为空对象或空字符串,如下例所示。例如: axios.post('your-end-point-url-here', '', config)
如果您不设置它,axios 将假定您作为第二个参数传递的任何内容都是 formData
const config = {
headers: { Authorization: `Bearer ${storage.getToken()}` }
};
axios
.post('http://localhost:8000/api/v1/get_token_payloads', {}, config)
.then(({ data: isData }) => {
console.log(isData);
})
.catch(error => {
console.log(error);
});
axios
本身带有两个有用的“方法”,即 interceptors
,它们只是请求和响应之间的中间件。所以如果你想在每个请求中发送令牌。使用 interceptor.request
。
我做了一个可以帮助你的包:
$ npm i axios-es6-class
现在您可以将 axios 用作类
export class UserApi extends Api {
constructor (config) {
super(config);
// this middleware is been called right before the http request is made.
this.interceptors.request.use(param => {
return {
...param,
defaults: {
headers: {
...param.headers,
"Authorization": `Bearer ${this.getToken()}`
},
}
}
});
this.login = this.login.bind(this);
this.getSome = this.getSome.bind(this);
}
login (credentials) {
return this.post("/end-point", {...credentials})
.then(response => this.setToken(response.data))
.catch(this.error);
}
getSome () {
return this.get("/end-point")
.then(this.success)
.catch(this.error);
}
}
我的意思是 middleware
的实施取决于您,或者如果您更喜欢创建自己的 axios-es6-class
https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a,它是它来自的媒体帖子
有很多好的解决方案,但我用这个
let token=localStorage.getItem("token");
var myAxios=axios.create({
baseURL: 'https://localhost:5001',
timeout: 700,
headers: {'Authorization': `bearer ${token}`}
});
export default myAxios;
然后我将 myaxios 导入我的文件并
myAxios.get("sth")
不定期副业成功案例分享
Bearer
应该与大写 B 一起使用,不是吗?