0

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

9
  • Why are you making your app configuration inside routes.js? Commented Aug 10, 2017 at 11:31
  • I am new to node and I want to keep the route in a separate module Commented Aug 10, 2017 at 11:37
  • That is fine but this is a configuration on your express settings, it is fine to keep your express related configs in your server.js. However, if you can add the usage inside routes.js maybe we can find a solution. Commented Aug 10, 2017 at 11:38
  • Nevermind I didn't see your routes.js already added. Now tell me this do you think app in routes.js refer to the same thing in server.js? Commented Aug 10, 2017 at 11:42
  • yes I think they both are same Commented Aug 10, 2017 at 11:45

3 Answers 3

2

Your app inside routes.js and server.js do not refer to the same thing. Hence your "app" won't work in routes.js. If you want to use app = express() in routes.js you can add something like this inside server.js

var Routes = require('./routes.js');
var r = new Routes(app);

so in order to instantiate routes like this your routes.js should look like:

module.exports = function(app){
    var login   = require ('./api/login');
    app.get('/login',login.authenticate);
    ...
}

Old answer:

As @Anurag Singh Bisht also answered you should allow Cross Domain requests. My answer would be slightly different:

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering but sorry this solution does not work.
0

You need to allow cross origin in your server, so that your front end can access it.

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, Authorization");
  next();
});

1 Comment

I have used this but its shows the same error but thanks for the help
0

You need to add below code for handling the preflight request sending from browser.

const cors = require('cors')
const corsOptions = {
  origin: '*'
}
app.use(cors(corsOptions))

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.