【问题标题】:How to fix: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)如何修复:JSON.parse (<anonymous>) 位置 0 处的 JSON 中的意外标记 <
【发布时间】:2018-03-19 09:24:39
【问题描述】:

我一直收到这篇文章标题中的错误。所以我从 response.json() 中删除了我的 .json() 我下面的代码return this.http.post('http://localhost:3000/sign-up', body, {headers: headers}) .map((response: Response) => response.json()) 但是,现在我得到了一个错误:

Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵    <base …src="/js/app/bundle.js"></script>↵</body>↵</html>",

我是 Web 开发的新手,我正在尝试使用我参加的在线课程中的代码。我知道我的 console.log 应该是一个对象,而不是这个“响应”。如何让我返回的数据成为我通过 html 表单提交的信息?

另外,我将 .json() 留在下面发布的代码中,这样它显示了我最初必须得到的 Unexpected token &lt; in JSON at position 0 at JSON.parse (&lt;anonymous&gt;) 错误。但就像我说的,我删除了那个 .json() 并得到了 Response {_body: "&lt;!DOCTYPE html&gt;↵&lt;html lang="en"&gt;↵&lt;head&gt;↵ &lt;base …src="/js/app/bundle.js"&gt;&lt;/script&gt;↵&lt;/body&gt;↵&lt;/html&gt;", 错误

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());
            // });
    }
}

下一课

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。
  • 我认为您正在获取带有 html 内容的纯文本并试图将其视为 json 字符串。
  • 你们介意再详细说明一下吗?就像我说的,我是 Web 开发的新手,所以我不知道如何改变这样的事情。谢谢!
  • 试试这个。忽略我关于 OOPS 的 cmets。希望这会有所帮助:stackoverflow.com/questions/41121284/…
  • @harold_mean2 你先生是我的英雄!你提出的链接没有我的具体修复,但它非常接近我的问题。如果不是你的链接,我从没想过会在那里检查

标签: json mongodb angular typescript mongoose


【解决方案1】:

问题在于您要返回的内容,您收到的是 HTML 内容,而您的代码需要 json 内容。您所要做的就是将您的服务器配置为返回json,或者修复您的代码以处理HTML 响应。

【讨论】:

  • 那么为什么response.json() 不能做到这一点呢?
  • .json() 函数负责将格式为JSON 符号的字符串转换为JSON 对象,您所拥有的不是JSON,而是格式为@987654330 @!所以.json()函数不能把它变成JSON对象
  • 但是const body = JSON.stringify(user); 不应该是您所指的JSON 格式的字符串吗?然后我打电话给.json()
  • 但是您并没有在 body 变量上调用 .json(),而是在您发布到 "http://localhost:3000/sign-up" 后从服务器返回的响应上应用它,这是一个 HTML 响应.
  • 那么我的解决方法是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
相关资源
最近更新 更多