node.js - Angular 4 : Unknown error after POST request to REST api on localhost

标签 node.js angular

Angular 应用程序正在尝试将用户数据发布到也在 localhost:8080 上运行的 Node.js Rest api。它是一个 HttpErrorResponse,状态为:0 且 StatusText:未知错误。其余 api 已通过向本地主机发出的curl 请求证明可以正常运行。任何有关此问题的帮助将不胜感激!

错误来自以下行:“this.http.post(' http://localhost:8080/users ' "

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    import { HttpClient } from '@angular/common/http';
    import { Headers } from '@angular/http';

    import { AuthService } from '../services/auth.service';
    import { Router } from '@angular/router';
    import { User } from '../models/user';

    import * as crypto from 'crypto-js';


    @Component({
      selector: 'app-sign-up-component',
      templateUrl: './sign-up.component.html',
      styleUrls: ['./sign-up.component.css']
    })
    export class SignUpComponent implements OnInit {
        signUpForm: FormGroup;
        username: FormControl;
        password: FormControl;
        email: FormControl;
        phonenumber: FormControl;

        user: User;
        constructor(private auth: AuthService, private http: HttpClient, private router: Router) {

}

ngOnInit() {
    this.createFormControls();
    this.createForm();
}

createFormControls() {
    this.username = new FormControl('', Validators.required);
    this.password = new FormControl('', [Validators.required, Validators.minLength(8)]);
    this.email = new FormControl('', [Validators.required, Validators.pattern("^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$")]);
    this.phonenumber = new FormControl('', [Validators.required, Validators.minLength(10), Validators.maxLength(10)]);
}

createForm() {
    this.signUpForm = new FormGroup ({
        username: this.username,
        password: this.password,
        email: this.email,
        phonenumber: this.phonenumber
    });
}

onSubmit() {
    if (this.signUpForm.valid) {
        // Create the new user
        this.user = new User(this.username, this.password, this.email, this.phonenumber);

        // Hash the password with SHA1
        var hashedPassword = crypto.SHA1(this.password.value);


    let headers = new Headers({'Content-Type' : 'application/json'});
        // POST the user to the backend
        this.http.post('http://localhost:8080/users', {
            username: this.username.value,
            password: hashedPassword.toString(),
            email: this.email.value,
            phonenumber: this.phonenumber.value
        }, headers).subscribe(
            res => {
                console.log(res);
                // Redirect to the login page after you sign up
                //this.router.navigate(['login']);
            },
            err => {
                console.log("there was an error");
            console.log(err);
            }
          );
    }
}

}

最佳答案

这是因为 Angular 有它自己的服务器端(可能是我选错了词),所有对 API 的请求默认都会发送到这一端,而不是你的 Node.js 服务器。为了解决这个问题,你可以使用代理。在项目根目录创建 proxy.config.json 文件。

proxy.config.json:

{
  "/test-route": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug"
  }
}

要启动您的项目,您必须在第一个终端中启动服务器,第二个终端中您应该使用以下命令启动 Angular:

ng serve --proxy-config proxy.config.json --watch

并且您的所有 API 调用都将被重定向到 http://localhost:8080(在本例中)。请注意,您需要保持 Angular 和服务器运行。

关于node.js - Angular 4 : Unknown error after POST request to REST api on localhost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626348/

相关文章:

node.js - 等到顺序 promise 解决后再在 Node 中继续

angular - 在延迟加载的模块被销毁时采取行动

angular - rxjs 和 WebStorm

Angular 2 - 在不显示 url 数据的情况下导航

javascript - 调试或查找代码中的某些拼写错误的简单方法是什么?

node.js - 命令gulp错误 "assert.js:42 throw new errors.AssertionError"

javascript - 如何从代码文本加载模块?

javascript - aws lambda 中的简单 node.js 示例

angular - fxFlex 不调整元素大小

javascript - 将 ngFor 列表中的按钮更改为文本字段以获取值,然后提交进行处理