skip to Main Content

I have 2 server.js files. One of them is inside the backend folder where when I run nodemon server.js on localhost:3000. And I’ll start angular with ng serve inside the angular folder and login to my app no problem. Everything works. No CORS issue.

BUT

If I try to run my server.js file in the root directory where express serves my angular build folder. It starts up on localhost:8080, but when I try to login to my app, I get

enter image description here

inside my app.js file I have the following, which should be relevant. Another thing worth noting
is I made a docker version and that version gives me the CORS error too. So it seems to only work when running locally with ng serve and nodemon server.js

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

  next();
});

server.js file in backend folder (localhost:3000 No CORS error)

const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();


const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});

server.js in root directory (localhost:8080 CORS error)

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
const userRoutes = require("./app/routes/user");
const appRoutes = require("./app/app");

const cors = require("cors");
app.use(morgan('dev'));


app.use(cors({ origin: 'http://localhost:8080' , credentials :  true}));var mongoose   = require('mongoose');
var path       = require('path');
var config = 'mongodb://azure45:[email protected]:33321/azure_chat'
//const app = require("./app");
const debug = require("debug")("node-angular");
var env = require("dotenv").config();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    next();
});


mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

app.use(express.static(__dirname + '/public/dist/glass/'));

//var apiRoutes = require('./app/app')(app, express);
app.use("/api/", appRoutes);
app.use("/api/user", userRoutes);

app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/dist/glass/index.html'));
});

app.listen(8080);
console.log('Magic happens on port ' + 8080);




const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);


const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};



Here’s the project file structure as a reference. app.js is where all my APIs are.

enter image description here

2

Answers


  1. Try to use Node.js CORS library for CORS.

    Something like below.

    const express = require("express");
    
    const cors = require("cors");
    
    const app = express();
    
    app.use(cors());
    
    Login or Signup to reply.
  2. With reference to rise’s answer:
    Add options to cors method:

    var corsOptions = {
    origin: 'your client url',
    optionsSuccessStatus: 200,
    

    }
    app.use(cors(corsOptions));

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search