1

enter image description hereI'am using Angular2 to submit a POST Request to node Application/Server which is running on localhost:4000. But I keep getting 404 Error - Page not found. The Node Sever/Application is running and I can test it via Postman... I get Response as expected. just via Angular2 App is doesn't work.

Ang2 Code:

import { Component, OnInit } from '@angular/core';
import { MdRadioModule, MdButtonModule } from '@angular/material';
import { Http, Headers } from '@angular/http';
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';


@Component({
   selector: 'app-signin',
   templateUrl: './login.component.html',
   styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {
   form: FormGroup;
   name = new FormControl();
   constructor(private http: Http, private fbuilder:FormBuilder) { }
   ngOnInit() {}

   login(mail:string, pass:string) {
      let headers = new Headers();
      let EMAIL_REGEXP = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/i;

      this.form = this.fbuilder.group({
          email: mail,
          password: pass
      });

      let formObj = this.form.getRawValue();
      let serializedForm = JSON.stringify(formObj);

      console.log( 'formObj: ' + formObj + '\n' 
            + 'this.form: ' + this.form + '\n' 
            + 'serializedForm: ' + serializedForm);

      if (!EMAIL_REGEXP.test(mail)) {
         return false;
      } else if (pass === '') {
         return false;
      } else {
        alert('Works!: ' + mail + 'pass: ' + pass);

        headers.append('Content-Type', 'application/json');

        this.http.post('http://localhost:4000/auth/sign_in', serializedForm, { headers })
            .subscribe(
                data => console.log('success!', data),
                error => console.error('Error caused by: ' + error)
            )

       }

    }

}

The View:

<section class="section--center" style="background-color:#fff; 
                   margin:0 auto !important; box-shadow: 0 0 2px 0 #000000; height:auto; min-height:90%;">
    <div class="login-form" layout="row" layout-align="space-around" layout-padding="layout-padding">
        <md-card class="card">
            <div md-toolbar>
                <div class="md-toolbar-tools">
                    <h2><span>Login Form</span></h2>
                </div>
            </div md-toolbar>
            <form #form="ngForm" method="POST">
                <div style="padding:10px 0 10px 20px;">
                    <md-input-container>
                        <label>email:</label>
                        <input mdInput name="email" [(ngModel)]="email" #inputMail required
                            pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$">
                              <md-error>
                                   This field is required
                              </md-error>
                    </md-input-container>
                </div>
                <div style="padding:10px 0 10px 20px;">
                    <md-input-container>
                        <label>password:</label>
                        <input mdInput name="password [(ngModel)]="password" #inputPass required="" md-maxlength="16">
                        <md-error>
                            This field is required
                        </md-error>
                    </md-input-container>
                </div>
                <br>
                <div class="button-row">
                    <button class="submit" md-button (click)="login(inputMail.value, inputPass.value)">Add</button>
                </div>
            </form>
        </md-card>

    </div>

</section>

Node: 'use strict';

    var mongoose = require('mongoose');
    var jwt = require('jsonwebtoken');
    var bcrypt = require('bcrypt');
    var User = mongoose.model('User');
    //mongoose.Promise = global.Promise;

    let mailer = require("nodemailer");
    let smtpTransport = require('nodemailer-smtp-transport');

   exports.sign_in = function (req, res) {
        User.findOne({
            email: req.body.email
        }, function (err, user) {
            if (err) throw err;
            if (!user || !user.comparePassword(req.body.password)) {
                return res.status(401).json({ message: 'Authentication failed. Invalid user or password.' });
            }
            return res.json(
                { 
                    token: jwt.sign(
                        { 
                            email: user.email, 
                            fullName: user.fullName, 
                            _id: user._id 
                        }, 
                        'RESTFULAPIs'
                    ) 
                }
            );
        });
    };

Node - server.js:

    let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let app = express();
let router = express.Router();

// DB Schema and User Schema
let Task = require('./public/js/_nodeTodos/todoListModel');
let User = require('./userDbModel');

// Routing Paths
let routes = require('./public/js/_nodeTodos/todoListRoutes');

// Mongo DB
let mongoose = require('mongoose');

// WebToken
let jsonwebtoken = require("jsonwebtoken");

// Server Port
let port = process.env.PORT || 4000;


mongoose.Promise = global.Promise;
// Connecting to "Tododb" Database
mongoose.connect('mongodb://localhost/Tododb');

// Add headers
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4000');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
app.use('/scripts', express.static(__dirname + '/node_modules/angular-utf8-base64/'));
app.use('/assets', express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());



app.use(function (req, res, next) {
    if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
        jsonwebtoken.verify(req.headers.authorization.split(' ')[1], 'RESTFULAPIs', function (err, decode) {
            if (err) req.user = undefined;
            req.user = decode;
            next();
        });
    } else {
        req.user = undefined;
        next();
    }
});

//let routes = require('./public/js/_nodeTodos/todoListRoutes');
routes(app);

app.use('/', function (req, res, next) {
    console.log('Request Url:' + req.url);
    next();
});

app.get('/apiPortal', function(req, res) {
    //res.render('index');
    console.log('The EndPoint: ' + req.url);
    res.sendFile('index.htm', { root: __dirname + "/" } );
});



app.listen(port);

Any Idea what could be the reason pls.?

k.vincent
  • 3,743
  • 8
  • 37
  • 74
  • Can you try adding `Access-Control-Allow-Origin` `*` to your header? – Christopher Jul 07 '17 at 13:14
  • do u have the code of nodejs ? – Dhyey Jul 07 '17 at 13:14
  • @Chris I think if it were `Access-Control-Allow-Origin` problem it wouldn't throw a 404 – Dhyey Jul 07 '17 at 13:15
  • Nevermind, that's a fair point @Dhyey – Christopher Jul 07 '17 at 13:15
  • Did you add a 404 handler in the back end? You could print the URL and request parameters to the console – Josef Hoppe Jul 07 '17 at 13:15
  • @Dhyey: Thanks, Node Code has been added. Do you need server.js? – k.vincent Jul 07 '17 at 13:28
  • @k.vincent IMO this is really weird, can u pls post screenshots of postman and this specific request in the network panel of devtools ? – Dhyey Jul 07 '17 at 13:33
  • not sure but may be `{ headers }` is not the right way. try `{ headers: headers }` – Ekansh Rastogi Jul 07 '17 at 13:39
  • I think we need to see what your request handler looks like. You may have set up a route incorrectly or you're calling the route incorrectly. It's hard to tell without knowing what your request handling/routes look like. – Jeff LaFay Jul 07 '17 at 13:42
  • @Ekansh Rastogi: passing headers as Object didn't help. – k.vincent Jul 07 '17 at 13:46
  • @jlafay: routing in node: `'use strict'; module.exports = function(app) {     var getUserCtrl = require('../_nodeControllers/userControllerMeth.js');     app.route('/auth/sign_in').post(getUserCtrl.sign_in);     /*app.route('/getpass/update').post(getUserCtrl.update);*/ };` – k.vincent Jul 07 '17 at 14:00
  • @Dhyey: Screenshot has been added. Thanks! – k.vincent Jul 10 '17 at 09:27
  • Could it be possible that there is a kind of conflict with the built-in "angular-in-memory-web-api" which I'm using in the same App but for another page/routing? – k.vincent Jul 10 '17 at 09:56

2 Answers2

0

This error come when your pre flight request failed.

In your app backend(probably in app.js) set the

Access-Control-Allow-Origin

to your front end or * for every request. This will allow your front end request.

Vishnu Mishra
  • 3,683
  • 2
  • 25
  • 36
0

The issue is solved... It has to do with the Angular InMemoryBackendService built-in service as I was make use of it in the same app for other component. This Angular built-in feature seems doing a kind of 'redirect' from http.get method... after commenting it out in app.component, it did work. Pls. refer to: AngularJS 2 : Getting data from json file not working

k.vincent
  • 3,743
  • 8
  • 37
  • 74