I am trying to connect my angular app to my node server and I don't want to keep my routes in server file so I have a node server file which looks like this
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
var router = express.Router();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var cors = require('cors');
app.use(cors())
var db ='mongodb://localhost:27017/demo'
mongoose.connect(db,function(err){
if(err){
console.log("err");
}
else{
console.log("coonected to db");
}
})
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.set('views', path.join(__dirname,'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
app.use(express.static(path.join(__dirname,'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',function(req,res){
console.log("you have reached server");
res.json('wtf');
})
module.exports = app;
require('./route.js');
app.listen(port);
In route.js I have my route like this
var login = require ('./api/login');
var app = require('./server')
app.get('/login',login.authenticate);
It works fine if I use it on node server but if I use it on angular server it shows this error:
Redirect from 'localhost:3000/login' to 'localhost:3000/login/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:4200' is therefore not allowed access.
It only happens to the routes that I define in route.js. If I define the same route in server.js they work fine.
PS: I have also used
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
and some variation of this code but nothing works if I want to route to login url which is in my route file