【问题标题】:Getting error while sending data from Postman using Node.js使用 Node.js 从 Postman 发送数据时出错
【发布时间】:2019-06-18 03:56:03
【问题描述】:

我在从 Postman 发送请求时收到以下错误,我正在使用 Node.js 作为后端。

错误:

POST /api/users/save-card-details 400 31.719 ms - 871
SyntaxError: Unexpected token -
    at parse (/opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/types/json.js:83:15)
    at /opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/read.js:116:18
    at invokeCallback (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:262:16)
    at done (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:251:7)
    at IncomingMessage.onEnd (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:307: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:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

我的代码如下:

server.js:

 var express=require('express');
    var morgan = require('morgan');
    var http=require('http');
    var bodyParser= require('body-parser');
    var methodOverride = require('method-override');
    var mongo = require('mongojs');
    var session = require('express-session');
    var app=module.exports=express();
    var server=http.Server(app);
    var port=8989;
    var admin=require('./route/route.js');
    var api=require('./api/api.js');
    app.use(express.static(__dirname + '/public'));     // set the static files location /public/img will be /img for users
    app.use(morgan('dev'));                     // log every request to the console
    app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' }))    // parse application/x-www-form-urlencoded
    app.use(bodyParser.json({limit: '5mb'}))    // parse application/json
    app.use(methodOverride());                  // simulate DELETE and PUT
    app.use(session({secret: 'FGDPlexel',resave: true,saveUninitialized: true}));
    app.get('/',function(req,res){
        res.sendFile(__dirname + '/index.html');
    })
app.post('/api/users/save-card-details',api.saveCardDetails);

api.js:

var multer  = require('multer');
var storage =multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './../uploads');
  },
  filename: function (req, file, callback) {
    callback(null, Date.now()+'-'+file.originalname);
  }
});
var upload = multer({ storage: storage });
exports.saveCardDetails=function(upload.single('image'),req,res){
    var name=req.body.name;
    var company=req.body.company;
    var position=req.body.position;
    var mobile=req.body.mobile;
    var email=req.body.email;
    var landline=req.body.landline;
    var url=req.body.url;
    var postcode=req.body.postcode;
    var address=req.body.address;
    var image=req.body.image;
    var userid=req.body.userid;
    var profiletext=req.body.profile;
    var biography=req.body.biography;
    var token_id=req.body.token_id;
    console.log('request',req);
}

这里我使用 postman 发送请求并设置标题 Content-Type:application/json 。屏幕截图如下。

这里我需要先上传图片,然后获取图片名称以及所有其他数据,但出现上述错误。

【问题讨论】:

  • 我认为问题在于您没有发送有效的 JSON。我会在 json.js 中打印一些内容来打印它实际​​收到的内容。
  • 我通过邮递员发送并设置标题Content-Type:application/json及其form-data
  • 但是如果您查看 json.js 代码,您会发现当请求正文不是有效的 JSON 时会发生错误。
  • 我检查并得到了这个if (first !== '{' && first !== '[') { debug('strict violation') throw new SyntaxError('Unexpected token ' + first) } 行。但是我正在使用第三方工具。能否请您分享解决方案。
  • 如果你在邮递员上点击批量编辑,在你的杰森响应的右上角,它会让你像普通的 JSON 格式一样编辑。愿它可以变得更容易找到解决方案

标签: node.js postman multer


【解决方案1】:

我不知道为什么,但看起来请求不包含有效的 JSON。

如果你会去

/opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/types/json.js:83:15)

你会看到这个函数

function parse(body) {
  if (body.length === 0) {
    return {}
  }

  if (strict) {
    var first = firstchar(body)

    if (first !== '{' && first !== '[') {
      debug('strict violation')
      throw new SyntaxError('Unexpected token ' + first) <--- Your error
    }
  }

  debug('parse json')
  return JSON.parse(body, reviver)
}

node.js 的好处是您可以轻松地动态更改库的代码。所以我会做一个console.logbody,看看实际发生了什么。

【讨论】:

  • 我按照你的要求做了,在控制台中我得到了许多二进制数据以及------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="userid" 1234 ------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="profile" wesd ------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="biography" wsde ------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="token_id" 1234567890
  • 没错。所以它根本不是 JSON。也许尝试另一种工具来发送请求。喜欢卷曲。这个答案可能对您有所帮助How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
  • 所以你明白了。也许您只是想像其他普通对象一样操作二进制格式
  • 还有 curl 发送图片吗?
  • 您不能在 JSON 中将图像作为“图像”发送 :)。如果您将其编码为 Base64 并尝试将其作为字符串发送可能会更好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2018-01-27
相关资源
最近更新 更多