如果您在使用axios进行POST请求时遇到问题,并且这个问题是与特定的React结构有关的,请尝试以下
确保您正确地引入了axios和React。
确保您正确地设置了axios的baseURL和headers选项。例如:
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
axios.post('/api/users', { name: 'John Smith', email: 'john@example.com' }) .then(response => { console.log(response); }) .catch(error => { console.log(error); });
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { isLoading: false, errorMessage: '' }; } handleSubmit = (event) => { event.preventDefault(); this.setState({isLoading: true}); axios.post('/api/users', { name: 'John Smith', email: 'john@example.com' }) .then(response => { console.log(response); this.setState({isLoading: false}); }) .catch(error => { console.log(error); this.setState({isLoading: false, errorMessage: 'An error occurred'}); }); } render() { return (
); } }尝试这些解决方法,看看是否有助于解决您遇到的问题。