SyntaxError:位于0的JSON中的意外标记u

时间:2018-05-16 11:29:39

标签: node.js visual-studio-code

我正在尝试导出邮递员收集的数据。我正在严格遵循这篇文章中的步骤:

http://blog.getpostman.com/2017/09/01/write-to-your-local-file-system-using-a-postman-collection/

但是,在那里提供的脚本必定存在一些问题,因为每次我在node.js上运行它都会出现以下错误,这也是在通过postman发出post请求时传递的:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>SyntaxError: Unexpected token u in JSON at position 0
            <br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)
            <br> &nbsp; &nbsp;at C:\Users\Pablo\Node\hlr.js:13:58
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (C:\Users\Pablo\Node\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at next (C:\Users\Pablo\Node\node_modules\express\lib\router\route.js:137:13)
            <br> &nbsp; &nbsp;at Route.dispatch (C:\Users\Pablo\Node\node_modules\express\lib\router\route.js:112:3)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (C:\Users\Pablo\Node\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at C:\Users\Pablo\Node\node_modules\express\lib\router\index.js:281:22
            <br> &nbsp; &nbsp;at Function.process_params (C:\Users\Pablo\Node\node_modules\express\lib\router\index.js:335:12)
            <br> &nbsp; &nbsp;at next (C:\Users\Pablo\Node\node_modules\express\lib\router\index.js:275:10)
            <br> &nbsp; &nbsp;at C:\Users\Pablo\Node\node_modules\body-parser\lib\read.js:130:5
        </pre>
    </body>
</html>

提供此错误的脚本如下:

var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // Body parser use JSON data

app.post('/launches', function(req, res) {

    var outputFilename = './spaceReport.json'; // path of the file to output

    fs.writeFileSync(outputFilename, JSON.stringify(JSON.parse(req.body.payload), null, 4)); // write to the file system

    res.send('Saved to ' + outputFilename);

});

var port = 3000;
app.listen(port);
console.log('Express started on port %d ...', port);

知道错误来自哪里?

1 个答案:

答案 0 :(得分:1)

可能JSON.stringify是不是有效JSON字符串的对象,您可以使用不JSON.parse的{​​{1}}

fs.writeFileSync(outputFilename, JSON.stringify(req.body.payload), null, 4);