【问题标题】:SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse in angular8SyntaxError:JSON 中的意外标记 U 在 angular8 中 JSON.parse 的位置 0
【发布时间】:2020-01-10 11:50:57
【问题描述】:

直到最近,当我更改以前代码的一些位和部分并注意到这个特殊错误时,我才避免了这个问题。

我使用 Angular 8、NodeJS 和 express 和 mongoose

每当我尝试传递特定对象或该对象的一部分时,我都会收到此错误(来自 chrome 控制台):

HttpErrorResponse {headers: HttpHeaders, status: 201, statusText: "Created", url: "http://localhost:3200/users/", ok: false, …}
error: {error: SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "Updated successfully!"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:3200/users/"
name: "HttpErrorResponse"
ok: false
status: 201
statusText: "Created"
url: "http://localhost:3200/users/"
__proto__: HttpResponseBase

这是在错误对象内:

message: "Unexpected token U in JSON at position 0"
stack: "SyntaxError: Unexpected token U in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:31668:51)
    at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3639:35)
    at Object.onInvokeTask (http://localhost:4200/vendor.js:94813:33)
    at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3638:40)
    at Zone.runTask (http://localhost:4200/polyfills.js:3407:51)
    at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:3720:38)
    at invokeTask (http://localhost:4200/polyfills.js:4835:18)
    at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:4872:25)"

奇怪的是,我得到了 201(“已创建”)的状态,并带有针对这种状态的指定文本消息(“已成功更新!”)。

我不是 100% 确定,但我认为错误源于 Headers 包,在解析正文时,因为我只从客户端收到此错误。

这些是我的 NodeJS 包:

"dependencies": {
    "bcrypt": "^3.0.6",
    "body-parse": "^0.1.0",
    "client-sessions": "^0.8.0",
    "connect": "^3.6.6",
    "cookie-parser": "~1.4.4",
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "dotenv": "^8.0.0",
    "express": "~4.16.1",
    "express-session": "^1.16.1",
    "express-validator": "^5.3.1",
    "http-errors": "~1.6.3",
    "mailgun-js": "^0.22.0",
    "moment": "^2.24.0",
    "mongoose": "^5.6.6",
    "morgan": "~1.9.1",
    "multer": "^1.4.2",
    "nodemon": "^1.19.1",
    "passport": "^0.4.0",
    "pug": "^2.0.4",
    "randomstring": "^1.1.5",
    "session": "^0.1.0",
    "session-mongoose": "^0.5.2",
    "util": "^0.12.1"
  }

这些是我的 Angular 包(不要介意'*',我最近有版本问题,版本是最新的稳定版本)

 "dependencies": {
    "@angular/animations": "*",
    "@angular/cdk": "*",
    "@angular/cli": "*",
    "@angular/common": "*",
    "@angular/compiler": "*",
    "@angular/core": "^8.2.4",
    "@angular/forms": "*",
    "@angular/http": "^7.2.15",
    "@angular/material": "^8.1.4",
    "@angular/platform-browser": "*",
    "@angular/platform-browser-dynamic": "*",
    "@angular/router": "*",
    "angular-cc-library": "^1.2.5",
    "angular-moment": "^1.3.0",
    "bootstrap": "^4.3.1",
    "core-js": "^3.2.1",
    "hammerjs": "^2.0.8",
    "moment": "^2.24.0",
    "ng2-search-filter": "^0.5.1",
    "rxjs": "~6.5.2",
    "save": "^2.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.803.2",
    "@angular/compiler-cli": "^8.2.4",
    "@angular/language-service": "^8.2.4",
    "@types/jasmine": "~3.4.0",
    "@types/jasminewd2": "~2.0.6",
    "@types/node": "~12.7.3",
    "codelyzer": "^5.1.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.2",
    "ts-node": "~8.3.0",
    "tslint": "~5.19.0"
  }

这是配置文件服务中的配置文件对象:

export class Profile {

    public selectedLanguage: number;  //language index
    public designer: string;
    public status: number;
    public Language: any;
    public languages = [
        "EN",
        "LT",
        "RU",
    ]

    constructor() {
    }
}

这是我用来更新语言索引的方法:

 sendLanguage() {
    this.http.put(this.key.key + 'users/', {
      selectedLanguage: this.profile.profile.selectedLanguage
    }, {
      headers: new HttpHeaders({'Content-Type': 'application/json'}),
      withCredentials: true
    }).subscribe(
      res => {
        console.log(res);
        this.profile.LanguageCheck();
      },
      err => {
        console.log(err);
      }
    )
  }

这是我通过路由调用的模块导出:

//user updates himself
exports.updateSelf = (req, res) => {
    //validate request
    if(!req.body){
        return res.status(400).send({
            message: "content can not be empty"
        });
    };
    //requesting authorization
    if(!req.session.user){
        return res.status(400).send({
            message: "You are not logged in!"
        });
    }

    User.findOneAndUpdate({_id: req.session.user.userID}, {
        selectedLanguage: req.body.selectedLanguage
    }, { new: true }).then(user => {
        if(!user){
            return res.status(404).send({
                message: "User not found"
            });
        }
        res.status(201).send("Updated successfully!");
    })
    .catch(err => {
        if(err.kind === 'ObjectId'){
            return res.status(404).send({
                message: "User not found"
            });
        }
        return res.status(500).send({
            message: "something went wrong while updating the user"
        });
    });
};

错误本身并不是什么大问题,因为它仍然保存数据,但它仍然困扰着我,因为我找不到它给我解析错误的原因。

【问题讨论】:

  • 你能发回信吗??
  • 您的成功回调发送的是字符串而不是对象。尝试将其更改为res.send({ message: 'Updated successfully' })
  • @Will Alexander 谢谢!这解决了问题,发布答案,我会将其标记为正确。
  • 哈哈不用担心人,不用污染线程^^
  • @WillAlexander 和 TonyNgo 啊,好吧,计时器刚刚结束,所以回复了帖子,再次感谢你们!

标签: node.js angular mongodb typescript angular8


【解决方案1】:

你有这个错误是因为当你的代码应该是 json 格式时你正在发送一个字符串响应

res.status(201).send("Updated successfully!");

因此您可以将代码更改为(将一些 json 数据发送回客户端)

res.status(201).send({message: 'Updated successfully'});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-21
    • 2021-06-30
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2020-04-12
    • 2019-09-23
    相关资源
    最近更新 更多