I'm developing a web site with VueJS, Nginx, Express and MongoDB. My backend works well if I make a PUT request pointing to the remote database from my local machine using the http protocol, but when I make the request from my local machine using the https protocol, or from the remote webpage hosted in the same server as the backend (which uses the https protocol), I get the message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.com:3000/markers/. (Reason: CORS request did not succeed)
The simplest solution should be to post from the webpage using the http (and not the https) protocol, but clearly it is not the best solution.
Relevant parts of my code are:
Fetch POST in my VueJS frontend:
async postData() { let url = 'https://www.example.com:3000/markers/' let data = { // My data } await fetch(url, { method: "POST", body: JSON.stringify(data), headers: {"Content-type": "application/json; charset=UTF-8","Access-Control-Allow-Origin": "*" } }).then(response => console.log(response.ok)) }
The server.js script in the backend:
const express = require('express')const mongoose = require('mongoose')const cors = require('cors');bodyParser = require('body-parser');const app = express()app.use(bodyParser.urlencoded({ extended: false }));app.use(bodyParser.json());app.use(bodyParser.json({ limit: "50mb" }))app.use(bodyParser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }))// CORSconst corsOptions = { origin: 'https://www.example.com:3000', credentials: false,}app.use(cors(corsOptions));mongoose.connect('mongodb://127.0.0.1/markers', {})const db = mongoose.connectiondb.on('error', (error) => console.log('ERROR!'))db.once('open', () => console.log('Connected to DB'))const markersRouter = require('./routes/markers')app.use('/markers', markersRouter)app.listen(3000, () => console.log('Server started!'))
The routes in the backend:
router.post('/', async (req, res) => { res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); res.setHeader('Pragma', 'no-cache'); res.setHeader('Expires', '0'); const marker = new Marker({ // My data }) try { const newMarker = await marker.save() res.status(201).json(newMarker) } catch (err) { res.status(400).json({ message: err.message }) } res.end();})
I've been two days looking for solutions, but the CORS "Learn more" documentation in the Mozilla webpage is really general regarding which are the causes of the error. The only answer found on the web that apply to my specific problem suggests the lines:
// CORSconst corsOptions = { origin: 'https://www.example.com:3000', credentials: false,}app.use(cors(corsOptions));
which I already add to my backend's server.js file, with no results, and the error remains the same.
Does somebody could tell me how to make the right request to make a fetch POST to the remote database via https?
All the best, and thanks a lot!