'react & nodeJS - HTTP always send OPTIONS instead regular methods
I tried to search about the issue a few days without understanding.
If you can explain how can I open all requests as regular and block 'OPTIONS' option it will be the best!
I'm trying to send HTTP PUT, GET, POST, DELETE methods with 'React' fetch. with POST, sometimes the server accept the requests, sometimes the fetch fails. with PUT / DELETE all the time the server getting OPTIONS request instead of the regular methods. I tried to learn about cors without a lot of understanding.
there are my backend and frontend example:
backend:
router.put('/privacy', (req, res) => {
let user = req.body.user,
decision = req.body.decision,
file = req.body.filename;
FileModel.findOne({'metadata.filename': file, 'uploadedBy': user}, function(err, file){
let errMsg = `change privacy of ${file} failed.`
if (err) {
res.json({
ok: false,
msg: errMsg
});
} else if (file) {
switch (decision) {
case 'private': {
file.isPrivate = true;
file.save();
res.json({
ok: true
});
break;
}
case 'public': {
file.isPrivate = false;
file.save();
res.json({
ok: true
});
break;
}
default: {
res.json({
ok: false,
msg: 'wrong decision'
});
}
}
} else {
res.json({
ok: false,
msg: errMsg
});
}
});
});
app.js (backend):
app.use(cors({ origin: 'http://localhost:3001' , credentials : true}));
app.use('/api', api);
front-end:
onSaveClicked = () => {
fetch('http://localhost:3000/api/manage/privacy', {
crossDomain: true,
credentials: 'include',
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: {
filename: this.state.name
}
}).then(res => res.json())
.then(json => json.result)
.then(result =>{
this.setState({files: result});
});
}
Thank you all.
Solution 1:[1]
You only need to alter the cors middleware options to
app.use(cors({ origin: '*' , credentials : true }))
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 | distanteagle16 |
