如何在 react axios 请求中添加值为 api 键的 header 字段
How to add a header field with value as api key in react axios request
要访问我的 api,我需要添加一个 header 字段:x-api-key 到 axios get 请求,其值为 api 键:12345678。
我怎样才能做到这一点以响应我当前的代码?
import "./App.css";
import axios from "axios";
import { useEffect } from "react";
function App() {
useEffect(() => {
axios
.get("https://challenge.movies.com.au/api/v2/blahblah/movies")
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
}, []);
return <div className="App"></div>;
}
export default App;
试试这个。
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
这里是 headers 在 axios 上的用法:
useEffect(() => {
axios.get("https://challenge.movies.com.au/api/v2/blahblah/movies", {
headers:{
'x-api-key': 'Bearer 12345678')
}
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
}, []);
你可以像那样简单地传递 headers
axios
.post(
"url",
{
key : value
},
{
headers: {
Authorization: "Bearer " + JSON.parse(token),
},
}
)
.then(async (response) => {
//Handel response here
})
.catch((error) => {
console.log(error);
});
要访问我的 api,我需要添加一个 header 字段:x-api-key 到 axios get 请求,其值为 api 键:12345678。 我怎样才能做到这一点以响应我当前的代码?
import "./App.css";
import axios from "axios";
import { useEffect } from "react";
function App() {
useEffect(() => {
axios
.get("https://challenge.movies.com.au/api/v2/blahblah/movies")
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
}, []);
return <div className="App"></div>;
}
export default App;
试试这个。
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
这里是 headers 在 axios 上的用法:
useEffect(() => {
axios.get("https://challenge.movies.com.au/api/v2/blahblah/movies", {
headers:{
'x-api-key': 'Bearer 12345678')
}
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
}, []);
你可以像那样简单地传递 headers
axios
.post(
"url",
{
key : value
},
{
headers: {
Authorization: "Bearer " + JSON.parse(token),
},
}
)
.then(async (response) => {
//Handel response here
})
.catch((error) => {
console.log(error);
});