I have a node js application where I forward form data from the client to the server to store this data there in a mongoDB.
To send the data to the server I use a POST request with API_URL: http://localhost/mews
.
Whenever the POST request is executed, I keep seeing a CORS error in the console of the client.
client side JS
const API_URL = "http://localhost/mews";
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
//Grab the form values
const name = formData.get('name');
const content = formData.get('content');
const mew = {
name,
content
}
//send the mew information to the server
const response = await fetch(API_URL, {
method: "POST",
body: JSON.stringify(mew),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log(json);
});
server side JS
const express = require('express');
const cors = require('cors');
const db = require('monk')('localhost/meower');
const mewe = db.get('mews');
var corsOptions = {
origin: 'http://localhost/mews',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
const app = express();
app.use(cors(corsOptions));
app.use(express.json());
function isValidMew(mew) {
return mew.name && mew.name.toString().trim() !== '' &&
mew.content && mew.content.toString().trim() !== '';
}
//chen user sends a message (POST)
app.post('/mews', async (req, res) => {
if (isValidMew(req.body)) {
const mew = {
name: req.body.name.toString(),
content: req.body.content.toString(),
created: new Date()
};
console.log(mew);
const createdMew = await mewe.insert(mew);
res.json(createdMew);
} else {
res.status(422);
res.json({
message: 'Hey! Name and Content are required!'
});
}
});
app.listen(4000, () => {
console.log("Listening on http://localhost:4000/");
});
ERROR in client console when making the post request
Cross-Origin Request Blocked: The Same Origin Policy does not allow reading of the remote resource at http: // localhost / mews. (Reason: CORS request was unsuccessful).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
this worked for me using "cors": "2.8.5"
const express = require('express');
const cors = require('cors');
const db = require('monk')('localhost/meower');
const mewe = db.get('mews');
const app = express();
app.use(express.json());
app.use(cors());
Hope it helps you too, the reference is in here https://www.npmjs.com/package/cors
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.