簡體   English   中英

Angular 4:在本地主機上向 REST api 發出 POST 請求后出現未知錯誤

[英]Angular 4: Unknown error after POST request to REST api on localhost

angular 應用程序試圖將用戶數據發布到也在 localhost:8080 上運行的 node.js rest api。 它是一個 HttpErrorResponse,狀態為:0 和 StatusText:未知錯誤。 通過向本地主機發出的 curl 請求,其余 api 已被證明是有效的。 對這個問題的任何幫助將不勝感激!

錯誤來自以下行:“ 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 在項目的根目錄下創建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 和服務器的運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM