我有一个有效的Rest API用axios编写。当我运行API并通过常规脚本进行调用时,一切都会按预期进行。当我从react项目进行相同的调用时,该调用未到达API,并且客户端获取并出错。
如果使用https://jsonplaceholder.typicode.com/todos/1
之类的外部API,则react调用可以正常工作
脚本调用:
import api from 'api'
api.get('/test')
.then(response => {console.log(response.data.msg)}) // Prints out a message
.catch(e => {console.log(e)})
react项目的调用:
import Form from "react-bootstrap/Form";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import Button from "react-bootstrap/Button";
import api from 'api'
const Workout = (props: any) => {
const handleSave = (e: any) => {
e.preventDefault();
console.log('Calling API') // This is printed so I know the code runs
api.get('/test')
.then(response => {console.log(response.data.msg)})
.catch(e => {console.log(e)}) // Prints out an error
};
return (
<tr>
<td colSpan={4}>
<Form onSubmit={handleSave}>
<Form.Group>
<Row>
<Col>
<Button
variant="primary"
type="submit"
onClick={handleSave}
>
Test
</Button>
</Col>
<Col></Col>
<Col></Col>
<Col></Col>
</Row>
</Form.Group>
</Form>
</td>
</tr>
);
};
api文件:
import axios from 'axios'
const api = axios.create({
baseURL: `/myApi`,
proxy: {
host: '127.0.0.1',
port: 4000
}
})
export default api
当我单击按钮时,我在控制台中看到Calling API
,然后出现此错误:
Error: Request failed with status code 404
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
答案 0 :(得分:1)
要在开发过程中执行此操作,请在您的package.json中添加"proxy": "http://localhost:4000"
。这样会将请求从运行端口转发到API所在的端口4000
以下是有关代理请求的反应文档以及解决方案起作用的原因:https://create-react-app.dev/docs/proxying-api-requests-in-development