简体   繁体   中英

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

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 )

bank.service.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.

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.

Place this on top of your app.module.ts for example :

// 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.

Once you have the value of what failed to be parsed, look for a matching log from the overwritten XMLHttpRequest.open . Inspect the request and you will see what the URL/endpoint is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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