带有Angular2的JSON发布到节点服务器返回404找不到的URL

时间:2017-07-07 13:12:00

标签: javascript json node.js angular

enter image description here我正在使用Angular2向在localhost:4000上运行的节点Application / Server提交POST请求。但我一直收到404错误 - 找不到页面。 Node Sever / Application正在运行,我可以通过Postman进行测试...... 我得到了预期的响应。只是通过Angular2应用程序是行不通的。

Ang2代码:

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)
            )

       }

    }

}

观点:

<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>

节点: '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'
                    ) 
                }
            );
        });
    };

节点 - 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);

任何想法可能是什么原因。

2 个答案:

答案 0 :(得分:0)

当你的预飞行请求失败时会出现此错误。

在您的应用后端(可能在app.js中)设置

  

访问控制允许来源

到您的前端或*为每个请求。 这将允许您的前端请求。

答案 1 :(得分:0)

问题解决了...... 它与Angular InMemoryBackendService内置服务有关,因为我在其他组件的同一个应用程序中使用它。这个角度 内置功能似乎正在做一种“重定向”#39;从http.get方法...在app.component中评论后,它确实有效。 PLS。请参阅:AngularJS 2 : Getting data from json file not working