I am making a webapp using the MEAN stack. The fact is that now I have developed a method to be able to register objects in the database, but when I execute it, an error results:
Response for preflight has invalid HTTP status code 404
I've been doing some research, and apparently it's in CORS. I mean, the problem is on my server. I go to app.js in the api part, made with NodeJS, and this is the code made:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS, DELETE');
res.header('Allow', 'GET, PUT, POST, OPTIONS, DELETE');
res.header('Content-Type', 'application/json; charset=utf-8');
return next();
});
Can you find out where the error exists? I've looked at other ways, but I can't find it.
The problem was that when executing the method that I had created for inserting new records in the database, I got an error. Doing some research, I came close to the solution apparently. Apparently, it was a problem related to CORS (Cross-Origin Resource-Sharing, in Castilian: Exchange of cross-origin resources), resulting in the error that I specified in the question.
My method for data collection was this (NodeJS):
and my model is this (Angular):
I noticed that the property "_id" and "_v" are created automatically once registered in the database. And my model in NodeJs was this:
What happened was that it sent a "project" object, created with the "_id" property, although it was empty, it did not match the NodeJs model. With what gave an error, an object with an extra property was created, and the server showed an internal error (500). Anyway, I needed the "_id" property to use in one of the Angular components, so I needed that property declared in the "Project" model, at least to the best of my knowledge, I got to the solution by rethinking the fetch method of data in the NodeJs controllers, leaving it like this:
In this way, it collected only the data that I needed to introduce a new record to the database. The "_id" field that still came empty was discarded, simply not using it. I hope this is of help to someone. As for me having a problem regarding CORS, it was due to a badly named path, but it's all fixed. Maybe it's a bad way to develop code, but hey, I'm getting my chest out. All the best.