SyntaxError: неожиданный токен # в JSON - PullRequest
0 голосов
/ 30 апреля 2018

Итак, я получаю эту ошибку, которую, очевидно, получает каждый второй угловой разработчик noob. Попытка провести некоторое тестирование на целевой странице, где я регистрирую электронные письма в своей базе данных, но каждый раз получаю эту синтаксическую ошибку.

ошибка

SyntaxError: Unexpected token # in JSON at position 0
    at Object.parse (native)
    at createStrictSyntaxError (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/types/json.js:157:10)
    at parse (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/types/json.js:83:15)
    at /Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:224:16)
    at done (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:273:7)
    at emitNone (events.js:86:13)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
SyntaxError: Unexpected token # in JSON at position 0
    at Object.parse (native)
    at createStrictSyntaxError (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/types/json.js:157:10)
    at parse (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/types/json.js:83:15)
    at /Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:224:16)
    at done (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:273:7)
    at emitNone (events.js:86:13)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
SyntaxError: Unexpected token # in JSON at position 0
    at Object.parse (native)
    at createStrictSyntaxError (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/types/json.js:157:10)
    at parse (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/types/json.js:83:15)
    at /Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:224:16)
    at done (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/Users/lorenzowhite/Desktop/Work Stuff/projectus/node_modules/raw-body/index.js:273:7)
    at emitNone (events.js:86:13)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)

landing.component.ts

import { Component, OnInit } from '@angular/core';
import { ValidateService } from '../../services/validate.service';
import { AuthService } from '../../services/auth.service'

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {
  email: String;

  constructor(
    private validateService: ValidateService,
    private authService: AuthService
  ) { }

  ngOnInit() {
  }

  onSubmit(){
    console.log(this.email)
    if(!this.validateService.validateEmail(this.email)){
      console.log("please use valid email")
      return false
    } else {
      this.authService.registerEmail(this.email).subscribe(data =>{
        if(data.success){
          console.log('you are now registered')
        } else {
          console.log('you are not registered')
        }
      })
    }
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
  authToken: any;
  userEmail: any;

  constructor(
    private http: Http
  ) { }

  registerEmail(userEmail){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let opts = {headers: headers}
    return this.http.post('http://localhost:3000/users/notifyme', userEmail, opts)
      .map(res => res.json())
  }

}

пользователи / notifyme route

const express = require('express');
const router = express.Router();

const User = require('../models/users')

router.post('/notifyme', (req, res, next) =>{
  let newUser = new User({
    email: req.body.email,
  })

  User.addEmail(newUser, (err, user)=>{
    if(err){
      res.json({success:false, msg: "failed to register"})
    } else {
      res.json({sucess:true, msg: "registered email"})
    }
  })})


module.exports = router;

, а затем функция addEmail буквально просто сохраняет электронную почту в БД.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...