Andrew Fox
Andrew Fox

Reputation: 69

NodeJS - No 'Access-Control-Allow-Origin' header

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;

Upvotes: 0

Views: 184

Answers (1)

Venkatesh A
Venkatesh A

Reputation: 2474

Try using this...

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

Upvotes: 1

Related Questions