I have a working Rest API written with axios. When I run the API and make a call through a regular script everything works as expected. When I make the same call from a react project, the call doesn't reach the API and the client gets and error.
The react call works fine if use an external API like https://jsonplaceholder.typicode.com/todos/1
The call from a script:
import api from 'api'
api.get('/test')
.then(response => {console.log(response.data.msg)}) // Prints out a message
.catch(e => {console.log(e)})
The call from the react project:
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>
);
};
The api file:
import axios from 'axios'
const api = axios.create({
baseURL: `/myApi`,
proxy: {
host: '127.0.0.1',
port: 4000
}
})
export default api
When I click the button I see Calling API in the console and then this error:
Error: Request failed with status code 404
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
baseURLto "localhost:3000"