JSON 中位置 0 的意外标记 U
Unexepected token U in JSON at position 0
我对 MEAN Stack 有疑问。
我有一个 Angular 表单,它具有良好的价值,可以在后端使用 Node Express 创建公司 ID 数据库。我有一个错误,Node 中的 JSON 未定义。但我不明白为什么?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const userboRoutes = require('./routes/userbo');
const companyRoutes = require('./routes/company');
const path = require('path');
mongoose.connect('mongodb://127.0.0.1/aya', {useNewUrlParser: true})
.then(() => {
console.log('Successfully connected to MongoDB AYA!');
})
.catch((error) => {
console.log('Unable to connect to MongoDB! AYA');
console.error(error);
});
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(bodyParser.json());
app.use('/api/company', companyRoutes);
app.use('/api/authbo', userboRoutes);
module.exports = app;
routes\company.js
const express = require('express');
const router = express.Router();
const companyCtrl = require('../controllers/company');
const Company = require('../models/company');
router.post('/', companyCtrl.createCompany);
router.get('/:id', companyCtrl.getOneCompany);
router.put('/:id', companyCtrl.modifyCompany);
router.delete('/:id', companyCtrl.deleteCompany);
router.get('/', companyCtrl.getAllCompany);
module.exports = router;
controller\company.js
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
Angular 分量:
this.companyService.CreateCoData(company).then(
() => {
this.CreateCoForm.reset();
this.router.navigate(['home']);
},
(error)=> {
this.loading = false;
this.errorMessage = error.message;
}
);
公司服务
import { Router } from '@angular/router';
import { Company } from './../models/company.model';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
export class CompanyService {
constructor(private router: Router,
private http: HttpClient) { }
company: Company[];
companySubject = new Subject<Company[]>();
public company$ = new Subject<Company[]>();
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
我收到这个错误:
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at exports.createCompany (E:\MEAN\BACKEND\controllers\company.js:7:29)
或者在请求负载(Chrome 开发工具网络)中 json 是正确的。
我不明白为什么 req json in undefined ?
请帮助我理解:)
更新
只需与 POSTMAN 一起工作:
并像这样更新 company.js
exports.createCompany = (req, res, next) => {
console.log( req.body);
// req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.coid,
coname: req.body.coname,
service: req.body.service,
address: req.body.address,
state: req.body.state,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
size: req.body.size,
domain: req.body.domain,
duns: req.body.duns,
tid1: req.body.tid1,
numid1: req.body.numid1,
tid2: req.body.tid2,
numid2: req.body.numid2,
tid3: req.body.tid3,
numid3: req.body.numid3,
bankname: req.body.bankname,
bicswift: req.body.bicswift,
iban: req.body.iban,
datecreat: req.body.datecreat,
bogid: req.body.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
我认为问题出在错误的数据格式上。但是如何正确设置呢?
.save function returns a callback and not a promise.
因此,如果您按如下方式修改您的请求处理程序,它将起作用:
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save(function (err, newCompany) {
if (err) {
return res.status(400).json({ error: error });
}
return res.status(201).json(newCompany);
});
};
所以我找到了解决方案^^ 很自豪** ((^o^)/)**
第一次post更新后,我发现问题是Content-type Error。
所以在 ** 公司服务** (Angular) 我将其添加到 Force JSON Type !
import { HttpClient, HttpClientModule,** HttpHeaders** } from '@angular/common/http';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company, **this.httpOptions**).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
我对 MEAN Stack 有疑问。
我有一个 Angular 表单,它具有良好的价值,可以在后端使用 Node Express 创建公司 ID 数据库。我有一个错误,Node 中的 JSON 未定义。但我不明白为什么?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const userboRoutes = require('./routes/userbo');
const companyRoutes = require('./routes/company');
const path = require('path');
mongoose.connect('mongodb://127.0.0.1/aya', {useNewUrlParser: true})
.then(() => {
console.log('Successfully connected to MongoDB AYA!');
})
.catch((error) => {
console.log('Unable to connect to MongoDB! AYA');
console.error(error);
});
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(bodyParser.json());
app.use('/api/company', companyRoutes);
app.use('/api/authbo', userboRoutes);
module.exports = app;
routes\company.js
const express = require('express');
const router = express.Router();
const companyCtrl = require('../controllers/company');
const Company = require('../models/company');
router.post('/', companyCtrl.createCompany);
router.get('/:id', companyCtrl.getOneCompany);
router.put('/:id', companyCtrl.modifyCompany);
router.delete('/:id', companyCtrl.deleteCompany);
router.get('/', companyCtrl.getAllCompany);
module.exports = router;
controller\company.js
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
Angular 分量:
this.companyService.CreateCoData(company).then(
() => {
this.CreateCoForm.reset();
this.router.navigate(['home']);
},
(error)=> {
this.loading = false;
this.errorMessage = error.message;
}
);
公司服务
import { Router } from '@angular/router';
import { Company } from './../models/company.model';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
export class CompanyService {
constructor(private router: Router,
private http: HttpClient) { }
company: Company[];
companySubject = new Subject<Company[]>();
public company$ = new Subject<Company[]>();
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
我收到这个错误:
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at exports.createCompany (E:\MEAN\BACKEND\controllers\company.js:7:29)
或者在请求负载(Chrome 开发工具网络)中 json 是正确的。
请帮助我理解:)
更新
只需与 POSTMAN 一起工作:
并像这样更新 company.js
exports.createCompany = (req, res, next) => {
console.log( req.body);
// req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.coid,
coname: req.body.coname,
service: req.body.service,
address: req.body.address,
state: req.body.state,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
size: req.body.size,
domain: req.body.domain,
duns: req.body.duns,
tid1: req.body.tid1,
numid1: req.body.numid1,
tid2: req.body.tid2,
numid2: req.body.numid2,
tid3: req.body.tid3,
numid3: req.body.numid3,
bankname: req.body.bankname,
bicswift: req.body.bicswift,
iban: req.body.iban,
datecreat: req.body.datecreat,
bogid: req.body.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
我认为问题出在错误的数据格式上。但是如何正确设置呢?
.save function returns a callback and not a promise.
因此,如果您按如下方式修改您的请求处理程序,它将起作用:
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save(function (err, newCompany) {
if (err) {
return res.status(400).json({ error: error });
}
return res.status(201).json(newCompany);
});
};
所以我找到了解决方案^^ 很自豪** ((^o^)/)**
第一次post更新后,我发现问题是Content-type Error。
所以在 ** 公司服务** (Angular) 我将其添加到 Force JSON Type !
import { HttpClient, HttpClientModule,** HttpHeaders** } from '@angular/common/http';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company, **this.httpOptions**).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}