首页 文章

Angular 4:对localhost上的REST api发出POST请求后出现未知错误

提问于
浏览
1

角度应用程序试图将用户数据发布到node.js rest api,该api也在localhost:8080上运行 . 它是一个HttpErrorResponse,状态为:0,StatusText:Unknown Error . 其余的api已通过向localhost发出的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);
            }
          );
    }
}

}

1 回答

  • 0

    它是's because Angular has it'自己的服务器端(可能是我选错了字),所有API请求默认都转到这一边,而不是你的node.js服务器 . 要解决此问题,您可以使用 proxy . 在项目的根目录下创建 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和服务器都在运行 .

相关问题