I deployed a server running Express.js to netlify.
Now i make a request (from another url) to an api-endpoint on the server and get the error “Access to XMLHttpRequest at ‘serverURL/endpoint’ from origin ‘clientURL’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”
Heres my server.js:
const express = require("express");
const serverless = require("serverless-http");
const cors = require('cors')
const bodyParser = require('body-parser');
const app = express();
app.use(cors())
const router = express.Router();
const uri = "MONGOURI"
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var mongoose = require('mongoose');
mongoose.connect(uri, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true});
var dateSchema = new mongoose.Schema({
date: String,
positions: String
});
var dateModel = mongoose.model('date', dateSchema);
var db = mongoose.connection;
router.post('/getPositions', cors(), (req, res) => {
var date = req.body.date;
db.on('error', function(error) {
res.status(400)
});
db.once('open', function() {
dateModel.findOne({ date: date }).exec(function (err, doc) {
if(err) {
res.status(400)
}
res.status(200).json(doc);
db.close()
});
});
});
app.use("/.netlify/functions/api", router)
module.exports.handler = serverless(app);
netlify.toml
[build]
functions = "functions"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
_headers
/*
Access-Control-Allow-Origin: *
What is especially strange is, that the very first request I do after I re-deploy the server works, from the second on it seems to be broken.
Thank you in advance