解决HTTP Post无效的JSON问题

时间:2017-08-27 13:25:34

标签: json restify

我尝试使用Restify和Postman发送Post数据来发送请求。

但无论我通过Post发送什么数据,都会收到以下错误:

{ InvalidContentError: Invalid JSON: Unexpected token o in JSON at position 1
    at Server.parseJson (/_code/aService/node_modules/restify/lib/plugins/jsonBodyParser.js:40:25)
    at next (/_code/aService/node_modules/restify/lib/server.js:1028:30)
    at f (/_code/aService/node_modules/once/once.js:25:25)
    at Server.readBody (/_code/aService/node_modules/restify/lib/plugins/bodyReader.js:73:13)
    at next (/_code/aService/node_modules/restify/lib/server.js:1028:30)
    at f (/_code/aService/node_modules/once/once.js:25:25)
    at parseJson (/_code/aService/node_modules/restify/lib/plugins/jsonBodyParser.js:74:16)
    at Server.parseBody (/_code/aService/node_modules/restify/lib/plugins/bodyParser.js:96:13)
    at next (/_code/aService/node_modules/restify/lib/server.js:1028:30)
    at f (/_code/aService/node_modules/once/once.js:25:25)
  jse_shortmsg: 'Invalid JSON: Unexpected token o in JSON at position 1',
  jse_info: {},
  message: 'Invalid JSON: Unexpected token o in JSON at position 1',
  body: 
   { code: 'InvalidContent',
     message: 'Invalid JSON: Unexpected token o in JSON at position 1' },
  context: null }

这是我清理过的代码...... 的 API.js

const baseRouter    = require('./routes/BaseRoutes');
const restify       = require('restify'),
    restifyPlugin   = require('restify').plugins,
    chalk           = require('chalk'),
    util            = require('util'),
    compression     = require('compression');
const env = process.env.ENVIRONMENT || 'development';
const server = restify.createServer({
    name: "Test API",
    version: "1.0.0",
    url: "localhost"
});
server.pre(restify.pre.sanitizePath()); // sanitizePath: cleans up duplicate or trailing / on the URL
server.pre(function (req, res, next) {
    logger.silly(chalk.yellow.bold(`Request:\n${req}`));
    return next();
});

// The "use" handler chains is executed after a route has been chosen to service the request
server.use(compression()); // compress all responses
server.use(restifyPlugin.acceptParser(server.acceptable)); // Accept header
server.use(restifyPlugin.authorizationParser()); // Authorization header
server.use(restifyPlugin.dateParser()); // expires requests based on current time + delta
server.use(restifyPlugin.queryParser({ mapParams: true })); // Parses URL query paramters into req.query
server.use(restifyPlugin.jsonp()); // parses JSONP callback
server.use(restifyPlugin.gzipResponse()); // gzips the response if client accepts it
server.use(restifyPlugin.bodyParser()); // parses POST bodies to req.body
server.use(restifyPlugin.jsonBodyParser({ mapParams: true })); // parses JSON POST bodies to req.body
server.use(restifyPlugin.acceptParser(server.acceptable));
server.use(restifyPlugin.fullResponse()); //

server.use(restifyPlugin.throttle({
    burst: 100, // the amount of requests to burst to
    rate: 50, // number of requests/second to allow
    username: true,
    overrides: {
        '192.168.1.1': {
            rate: 0,        // unlimited
            burst: 0
        }
    }
}));
// When a client request is sent for a route that exist, but has a content-type mismatch, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 415 handler. It is expected that if you listen for this event, you respond to the client.
server.on('InvalidContent', function (req, res, err, cb) {
    console.log("line 122");
    logger.error(chalk.red.bold(util.inspect(err)));
    res.send();
});
// Emitted after a route has finished all the handlers you registered. You can use this to write audit logs, etc. The route parameter will be the Route object that ran.
server.on('after', function (req, res, route) {
    logger.verbose(chalk.green.bold(`Route:\n ${util.inspect(route)}`));
    logger.silly(chalk.green.bold(`Response:\n ${util.inspect(res)}`));
    logger.verbose(chalk.green.bold(`${res}`));
    logger.info(chalk.magenta.bold(`Request began at ${req.time()}ms`));
    logger.verbose(chalk.green.bold(`status code: ${res.statusCode}`));
    logger.verbose(chalk.green.bold(`data: ${res._data}`));
});

// *** apply routes...
baseRouter.applyRoutes(server, process.env.ROUTE_PREFIX);

// Lift Server -- the server is up...the force is alive!
server.listen(process.env._PORT, function () {
    logger.info(chalk.cyan.bold(`>>> >>>>> >>>>>>> ${server.name} is up!`));
    elapsedTime("");

    logger.verbose();
    logger.info(chalk.yellow(`Server listening on port: ${String(process.env._PORT)}`));
    logger.info(chalk.yellow(`Current Log Level set to: ${String(logger.transports.console.level)}`));

    logger.verbose(chalk.green.bold(`memory usage: ${Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100} MB`));
    logger.verbose(chalk.green.bold(`uptime: ${util.inspect(process.uptime())}`));
    logger.verbose(chalk.green.bold(`pid: ${util.inspect(process.pid)}`));

    logger.verbose(chalk.magenta.bold('loaded modules...'));
    logger.verbose(
        Object.keys(require('../package.json').dependencies).forEach(function (key) {
            let _obj = require('../package.json').dependencies[key];
            logger.verbose(chalk.magenta(`${key} : ${_obj}`));
        })
    );


});

BaseRoutes.js

const chalk     = require('chalk'),
    util        = require('util'),
    _Router     = require('restify-router').Router,
    router      = new _Router(),
    errors      = require('restify-errors');

function hello(req, res, next) {
    if (!req.is('application/json')) {
        return next(new errors.InvalidContentError("Expects 'application/json'"));
    }

    logger.info(chalk.yellow.bold(`Requested route: /api/v1/hello`));
    res.send('ok');
    next();
}

router.post({path: '/hello', version: '1.0.0'}, hello);

module.exports = router;

这是我发布的JSON

{
    "name": "John Smith"
}

正如你所看到的 - 我没有做任何与众不同的事情......但是我遇到了错误的#34;'无效的JSON:在位置1的JSON中出现意外的令牌o&# 39;"

我错过了什么?

1 个答案:

答案 0 :(得分:0)

您不能同时使用bodyParserjsonBodyParser中间件 - 您必须选择其中一个。

我遇到了同样的错误消息,当我删除了bodyParser中间件并且只使用了jsonBodyParser时,错误就消失了 - 我的猜测是bodyParser正在做某事操纵请求体,以便jsonBodyParser获取它时,它不再是格式良好的JSON,并且无法正确解析。