'Trouble establishing proxy connection from React frontend to Express backend
I am having trouble sending a JSON object using POST method from React frontend to Express Backend. I get the following error when I submit the form: Access to XMLHttpRequest at 'http://localhost:8080/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Any help will be much appreciated. I do not want to enables CORS due to security implications, and setting proxy parameter in package.json of the React project is not working.
Here is some of my code:
const handleSubmit = e => {
e.preventDefault();
if(entry !== "" && dueDate > Date.now()){
console.log({entryDate: entryDate, entry: entry, dueDate: dueDate});
axios({
method: 'post',
url: 'http://localhost:8080/create',
data: {
entryDate: entryDate,
entry: entry,
dueDate: dueDate
}
})
.then(response => response.json)
.then(data => {
console.log(`Success:: ${data}`)
})
.catch(e => {
console.log(`error: ${e}`)
})
toggle();
} else {
console.log("error")
}
}
<div>
<Modal toggle={toggle} isOpen={modal} >
<ModalHeader>Create Item</ModalHeader>
<ModalBody>
<Form>
<FormGroup>
<Label for="date">Date</Label>
<DatePicker id="entryDate" name="entryDate" onChange={onEntryDateChange} selected={entryDate}/>
</FormGroup>
<FormGroup>
<Label for="TODO">TODO</Label>
<Input type="textarea"
id="entry"
name="entry"
placeholder="Enter TODO here"
onChange={onEntryChange}/>
</FormGroup>
<FormGroup>
<Label for="dueDate">Due date</Label>
<DatePicker id="dueDate" name="dueDate"onChange={onDueDateChange} selected={dueDate}/>
</FormGroup>
</Form>
</ModalBody>
<ModalFooter>
<Button color="success" block type="submit" onClick={handleSubmit}>Create <FontAwesomeIcon icon={faPlus} size="sm"/></Button>
</ModalFooter>
</Modal>
</div>
)
}
// package.json - I have set the proxy to localhost:8080: ...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080",'
...
Solution 1:[1]
SOLVED
I ended up using axios.post function with url string not including excluding localhost:8080. It seems like since its already specified proxy url in package.json file, I don't have to do it again when making a post call with axios.
Here's the updated code:
axios
.post('/create', data)
.then((response) => response.json)
.then((data) => {
console.log(`Success:: ${data}`);
})
.catch((e) => {
console.log(`error: ${e}`);
});
Thanks anyways!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mario Petrovic |
