我正在构建一个艺术家搜索React应用程序,该应用程序可以访问Ticketmaster API,并应在登录之前和登录后返回结果。
登录后我得到401(未授权)。
search.js
import React, {Component} from 'react';
import axios from 'axios';
import {withRouter} from 'react-router-dom';
import {Form, FormControl, Button} from 'react-bootstrap';
import './style.css';
class SearchField extends Component {
state = {
search: ""
};
handleChange = (event) => {
const {name, value} = event.target;
this.setState({[name]: value.toLowerCase()});
};
apiCall = () => {
const ticketmasterURL = "https://app.ticketmaster.com/discovery/v2/events.json?keyword=";
const searchKey = process.env.REACT_APP_TM_KEY;
const term = this.state.search.split(" ").join("+");
axios.get("https://cors-anywhere.herokuapp.com/" + ticketmasterURL + term + "&apikey=" + searchKey)
.then(res => {
this.props.history.push({
pathname: "/events/",
search: `?${this.state.search.split(" ").join("+")}`,
state: {data: JSON.stringify(res.data._embedded.events)}
})
})
.catch(err => console.log(err));
};
handleSubmit = (event) => {
event.preventDefault();
this.apiCall();
//set the redirect state to true
this.setState({redirect: true});
};
render(){
return (
<div className="search-container">
<Form onSubmit={this.handleSubmit}>
<Form.Group>
<FormControl
type="text"
placeholder="Search"
name="search"
value={this.state.search}
onChange={this.handleChange}
/>
<div className="searchbtn-container">
<Button type="submit">Submit</Button>
</div>
</Form.Group>
</Form>
</div>
)
}
}
export default withRouter(SearchField);
app.js
import setAuthToken from './_helpers/setAuthToken';
import { setCurrentUser, logoutUser } from "./actions/authAction";
if (localStorage.jwtToken) {
const token = localStorage.jwtToken;
setAuthToken(token);
const decoded = jwt_decode(token);
Store.dispatch(setCurrentUser(decoded));
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
Store.dispatch(logoutUser());
window.location.href = "/login";
}
}
setAuthToken.js
import axios from 'axios';
const setAuthToken = (token) => {
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
delete axios.defaults.headers.common["Authorization"];
}
};
export default setAuthToken;
我认为我已将问题本地化为app.js中的setAuthToken函数,因为没有它,它可以工作,但不确定。
答案 0 :(得分:1)
您需要添加令牌的类型,因此:
axios.defaults.headers.common['Authorization'] = "Bearer " + token;