0

I have a NodeJS express server running on port 3000 with https and I'm calling the URL on another website also on https but it's getting blocked by the CORS policy - "No 'Access-Control-Allow-Origin' header is present on the requested resource."

This is my code:

const Express = require("express");
const express = require('express');
const http = require('https');
const fs = require('fs');

var privateKey = fs.readFileSync('key.key');
var certificate = fs.readFileSync('cert.pem');
var options = {key: privateKey,cert: certificate};

var app = Express();
var users = require('./routes/users');
var notifications = require('./routes/notifications');
var events = require('./routes/events');
var projects = require('./routes/projects');

app.use('../uploads', express.static('public'));
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    next();
 });

app.use('/api/v1/users', users);
app.use('/api/v1/projects', projects);
app.use('/api/v1/events', events);
app.use('/api/v1/notifications', notifications);

var server = http.createServer(options, app);
server.listen(3000 , '0.0.0.0', function() { 
    console.log("Server started") 
});
module.exports = server;
Andrew Fox
  • 69
  • 1
  • 7
  • Does this answer your question? [Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?](https://stackoverflow.com/questions/7067966/why-doesnt-adding-cors-headers-to-an-options-route-allow-browsers-to-access-my) – Willian Jul 03 '20 at 15:29

1 Answers1

1

Try using this...

const cors = require("cors");
const app = express();
app.use(cors());

Venkatesh A
  • 1,875
  • 1
  • 19
  • 23