简体   繁体   English

JSON 中位置 0 处的意外标记 N,用于 Angular 中的 post 方法

[英]Unexpected token N in JSON at position 0 for post method in angular

I am getting the below error in angular my backend is java我在 angular 中收到以下错误,我的后端是 java

SyntaxError: Unexpected token N in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad ( http://localhost:4200/vendor.js:10132:51 ) at ZoneDelegate.invokeTask ( http://localhost:4200/polyfills.js:3626:31 ) at Object.onInvokeTask ( http://localhost:4200/vendor.js:73280:33 ) at ZoneDelegate.invokeTask ( http://localhost:4200/polyfills.js:3625:60 ) at Zone.runTask ( http://localhost:4200/polyfills.js:3403:47 ) at ZoneTask.invokeTask [as invoke] ( http://localhost:4200/polyfills.js:3700:34 ) at invokeTask ( http://localhost:4200/polyfills.js:4838:14 ) at XMLHttpRequest.globalZoneAwareCallback ( http://localhost:4200/polyfills.js:4875:21 ) SyntaxError:JSON.parse () at XMLHttpRequest.onLoad ( http://localhost:4200/vendor.js:10132:51 ) at ZoneDelegate.invokeTask ( http://localhost:4200/ polyfills.js:3626:31 ) 在 Object.onInvokeTask ( http://localhost:4200/vendor.js:73280:33 ) 在 ZoneDelegate.invokeTask ( http://localhost:4200/polyfills.js:3625:60 )在 Zone.runTask ( http://localhost:4200/polyfills.js:3403:47 ) 在 ZoneTask.invokeTask [as invoke] ( http://localhost:4200/polyfills.js:3700:34 ) 在 invokeTask ( http ://localhost:4200/polyfills.js:4838:14 ) 在 XMLHttpRequest.globalZoneAwareCallback ( http://localhost:4200/polyfills.js:4875:21 )

bank.service.ts银行服务.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Bank } from './bank';

@Injectable({
  providedIn: 'root'
})
export class BankService {

  private baseurl='http://localhost:8080/';

  constructor(private http:HttpClient) { }

  getAllCustomers():Observable<any>{
    return this.http.get('http://localhost:8080/allbank');
  }

  addCustomer(bank:Bank):Observable<any>{
    console.log(bank)
    return this.http.post(this.baseurl+'bank',bank);
  }

  getCustomer():Observable<any>{
    return this.http.get('{$this.baseurl}/bank/${id}');
  }


}

Component成分

import { Component, OnInit } from '@angular/core';
import { BankService } from '../bank.service';
import { Bank } from '../bank';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-add-customer',
  templateUrl: './add-customer.component.html',
  styleUrls: ['./add-customer.component.css']
})
export class AddCustomerComponent implements OnInit {

  constructor(private bankService:BankService) { }
  bank:Bank=new Bank();
  submitted=false;

  ngOnInit() {
    this.submitted=false;
  }
  banksaveform=new FormGroup({
    bankcustid:new FormControl(),
    bankcustname:new FormControl(),
    bankcustbalance:new FormControl(),
    bankcustpassword:new FormControl()
  })

  saveCustomer(saveCustomer)
  {
    this.bank=new Bank();
    this.bank.cust_id=this.banksaveform.get("bankcustid").value;
    this.bank.cust_name=this.banksaveform.get("bankcustname").value;
    this.bank.cust_balance=this.banksaveform.get("bankcustbalance").value;
    this.bank.cust_password=this.banksaveform.get("bankcustpassword").value;
    this.submitted=true;
    this.save();
  }

  save()
  {
    this.bankService.addCustomer(this.bank)
    .subscribe(data=>console.log(data),error=>console.log(error));
    this.bank=new Bank();
  }

  addCustomerForm()
  {
    this.submitted=false;
    this.banksaveform.reset();
  }

}

This happens when you make some HTTP request and try to parse the response, but the response is not in the JSON format.当您发出一些 HTTP 请求并尝试解析响应,但响应不是 JSON 格式时,就会发生这种情况。

Something useful that you can do in order to hunt the source of this bug (in case you have a heavy website with a lot of outgoing requests) is to override the JSON.parse() and XMLHttpRequest.open() methods.为了寻找此错误的来源(如果您有一个包含大量传出请求的繁重网站),您可以做的一些有用的事情是覆盖JSON.parse() and XMLHttpRequest.open()方法。

Place this on top of your app.module.ts for example :将它放在app.module.ts ,例如:

// Override JSON.parse for debug purposes
(function () {
    var parse = JSON.parse;

    JSON.parse = function (str) {
        try {
            return parse.apply(this, arguments);
        } catch (e) {
            console.log('Error parsing', arguments);
            throw e;
        }
    }
}());


// Override XMLHttpRequest.open
(function() {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
        this.addEventListener('load', function() {
            console.log('Http Response', this.responseText, this);
        });
        origOpen.apply(this, arguments);
    };
})();

When trying to parse something that is not JSON, anywhere in your code, the overwritten JSON.parse will leave a log.当尝试解析不是 JSON 的内容时,在代码中的任何地方,被覆盖的JSON.parse都会留下日志。

Once you have the value of what failed to be parsed, look for a matching log from the overwritten XMLHttpRequest.open .获得解析失败的值后,从覆盖的XMLHttpRequest.open查找匹配的日志。 Inspect the request and you will see what the URL/endpoint is.检查请求,您将看到 URL/端点是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM