0

I am currently working on a sign-up page using Angular front-end and node.js back-end. Everything went fine until I got the following error. "Error.json() is not an error". I console.logged the error in my service to see what went wrong and it gave me the error below. I'll also add my other files, I don't see anything wrong, but I hope you guys can.

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.js?7a71:1091)
    at MapSubscriber.eval [as project] (auth.service.ts?b03b:22)
    at MapSubscriber._next (map.js?c4af:79)
    at MapSubscriber.Subscriber.next (Subscriber.js?215e:90)
    at XMLHttpRequest.onLoad (http.js?7a71:1591)
    at ZoneDelegate.invokeTask (zone.js?fad3:421)
    at Object.onInvokeTask (core.js?223c:4724)
    at ZoneDelegate.invokeTask (zone.js?fad3:420)
    at Zone.runTask (zone.js?fad3:188)
    at ZoneTask.invokeTask [as invoke] (zone.js?fad3:496)
    at invokeTask (zone.js?fad3:1517)
    at XMLHttpRequest.globalZoneAwareCallback (zone.js?fad3:1543)

node.js log

C:\Users\TijlD\Desktop\projects\09 Custom Seed>npm start

> udemy-nodejs-angular2@1.0.0 start C:\Users\TijlD\Desktop\projects\09 Custom Seed
> node ./bin/www

GET /signup 304 61.871 ms - -
GET /stylesheets/style.css 304 6.685 ms - -
GET /js/app/bundle.js 304 10.482 ms - -
GET /favicon.ico 304 3.088 ms - -
POST /user/ 200 20.115 ms - 695

my server side user route that is supposed to add a new member to my database

var express = require('express');
var router = express.Router();
var User = require('../models/user');
var bcrypt = require('bcryptjs');


router.post('/', function(req, res, next) {
    var user = new User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        password: bcrypt.hashSync(req.body.password, 10),
        email: req.body.email
    });
    console.log(user)
    user.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });
        }
        res.status(201).json({
            message: 'User created',
            obj: result
        });
    })
});

module.exports = router;

Angular service file: authentication.service.ts

import {User} from "./user.model";
import {Injectable} from "@angular/core";
import {Http, Response, Headers} from "@angular/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/rx';



// We need @injectable if we want to use http
@Injectable()

export class AuthService {

    constructor(private http: Http){}

    signup(user: User) {
        const body = JSON.stringify(user);
        const headers =  new Headers({'Content-Type': 'application/json'});
        console.log(body);
        return this.http.post('http://localhost:3200/user/', body, {headers: headers})
            .map((response: Response) => {
                const result = response.json();
                return result
            })
            .catch((error: any) => {
                console.log(error)
                return Observable.throw(error.json())
            })
    }

}

signup component

import {Component, OnInit} from "@angular/core";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {AuthService} from "./auth.service";
import {User} from "./user.model";
import {Router} from "@angular/router";

@Component({
    selector: 'app-signup',
    templateUrl: './signup.component.html'
})

export class SignupComponent implements OnInit {
    myForm: FormGroup;

    constructor(private authService: AuthService, private route: Router) {}

    onSubmit() {
        const user =  new User(
            this.myForm.value.email,
            this.myForm.value.password,
            this.myForm.value.firstName,
            this.myForm.value.lastName
        );
        console.log(user);
        this.authService.signup(user)
            .subscribe(
                data => {
                        console.log(data)
                        ,
                        error => console.error(error)
                }
            );
    }

    ngOnInit() {
        this.myForm = new FormGroup({
            firstName: new FormControl(null, Validators.required),
            lastName: new FormControl(null, Validators.required),
            email: new FormControl(null, Validators.required),
            password: new FormControl(null, Validators.required),
        });
    }
}
tilly
  • 2,229
  • 9
  • 34
  • 64
  • The error is pretty straightforward here. Whatever the error object is in `return Observable.throw(error.json())` does not have a function called `json()`. – rmlan Jan 25 '18 at 16:14
  • and how can I fix this? – tilly Jan 25 '18 at 16:15
  • And do you have an idea on what makes the "SyntaxError: Unexpected token < in JSON at position 0" error occur? – tilly Jan 25 '18 at 16:17
  • 1
    So this is two different questions in one. Please limit it to one question per post, and consider posting an [MCVE](https://stackoverflow.com/help/mcve) for the first problem. – rmlan Jan 25 '18 at 16:18
  • See: https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0-in-react-app – rmlan Jan 25 '18 at 16:19

0 Answers0