I kept getting the error in the title of this post. So I removed my .json() from response.json() my below code
return this.http.post('http://localhost:3000/sign-up', body, {headers: headers}) .map((response: Response) => response.json())
However, now I am getting as an error:如何解決:意外標記<在JSON在位置0的JSON.parse(<anonymous>)
Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵ <base …src="/js/app/bundle.js"></script>↵</body>↵</html>",
我是新來的網絡發展,我試圖從聯機當然,我花了使用代碼。我知道我的console.log應該是一個對象而不是這個'Response'。我如何獲得我返回的數據是我通過html表單提交的信息?
此外,我將我的代碼中的.json()留在下面,它顯示了我原來必須得到的Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)
錯誤。但是就像我說的,我刪除上傳.json(),並得到了Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵ <base …src="/js/app/bundle.js"></script>↵</body>↵</html>",
錯誤
import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import 'rxjs/Rx';
import { Observable } from "rxjs";
import { User } from "./user.model";
import { ErrorService } from "../errors/error.service";
@Injectable()
export class AuthService {
constructor(private http: Http, private errorService: ErrorService) {}
signup(user: User) {
const body = JSON.stringify(user);
const headers = new Headers({'Content-Type': 'application/json'});
return this.http.post('http://localhost:3000/sign-up', body, {headers: headers})
.map((response: Response) => response.json());
// .catch((error: Response) => {
// this.errorService.handleError(error.json());
// return Observable.throw(error.json());
// });
}
}
Next Class
import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { AuthService } from "./auth.service";
import { User } from "./user.model";
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html'
})
export class SignupComponent implements OnInit {
myForm: FormGroup;
constructor(private authService: AuthService) {}
onSubmit() {
const user = new User(
this.myForm.value.email,
this.myForm.value.password,
this.myForm.value.firstName,
this.myForm.value.lastName,
this.myForm.value.age,
this.myForm.value.goal
);
this.authService.signup(user)
.subscribe(
data => console.log(data),
error => console.error(error)
);
this.myForm.reset();
}
ngOnInit() {
this.myForm = new FormGroup({
firstName: new FormControl(null, Validators.required),
lastName: new FormControl(null, Validators.required),
email: new FormControl(null, [
Validators.required,
Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
]),
password: new FormControl(null, Validators.required),
age: new FormControl(null, Validators.required),
goal: new FormControl(null, Validators.required)
});
}
}
可能是服務器返回null,無法解析爲json。 – NiVeR
我認爲你得到的HTML內容純文本,並試圖把它作爲一個JSON字符串。 –
你們會介意再詳細一點嗎?就像我說的,我是網絡開發的新手,所以我不知道如何改變這樣的事情。謝謝! – XXIV