范围错误:无效的状态代码:0

时间:2017-09-20 11:50:13

标签: node.js visual-studio

我是nodejs的新手,我使用visual studio 2015 web express来了解node js开发。 每件事都很好,并且顺利运行​​简单的app.get方法,现在我想从nodejs中检索一些列表,但它不起作用。

我已阅读一篇文章并尝试实施。 Check here

我有以下代码:

var http = require('http');
var express = require('express');

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

var port = process.env.port || 1337;

var app = express();
 app.use(bodyParser.urlencoded({ 
extended: true
}));


app.get('/api/list', function (request, response) {
response.status(200).json(
    { "movieId": 1, "name": "The Pacific Rim" },
    { "movieId": 2, "name": "Transformer" });
});

app.listen(port);

当我访问" http://localhost:1337/api/list"

时,我在浏览器中收到以下错误
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:574:10)
at ServerResponse.send (c:\users\XYZ12\documents\visual studio 2015\Projects\NodeMovieList\NodeMovieList\node_modules\express\lib\response.js:211:10)
at ServerResponse.json (c:\users\XYZ12\documents\visual studio 2015\Projects\NodeMovieList\NodeMovieList\node_modules\express\lib\response.js:256:15)
at ServerResponse.send (c:\users\XYZ12\documents\visual studio 2015\Projects\NodeMovieList\NodeMovieList\node_modules\express\lib\response.js:158:21)
at c:\users\XYZ12\documents\visual studio 2015\Projects\NodeMovieList\NodeMovieList\server.js:22:14
at Layer.handle [as handle_request] (c:\users\XYZ12\documents\visual studio 2015\Projects\NodeMovieList\NodeMovieList\node_modules\express\lib\router\layer.js:95:5)
at next (c:\users\XYZ12\documents\visual studio 2015\Projects\NodeMovieList\NodeMovieList\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (c:\users\XYZ12\documents\visual studio 2015\Projects\NodeMovieList\NodeMovieList\node_modules\express\lib\router\route.js:112:3)

1 个答案:

答案 0 :(得分:0)

您实际上并没有向响应发送数组,而是传递了第二个参数,即状态代码参数。

这是您的代码

json(
    { "movieId": 1, "name": "The Pacific Rim" },
    { "movieId": 2, "name": "Transformer" }
);

这是你应该做的:

json([
        { "movieId": 1, "name": "The Pacific Rim" },
        { "movieId": 2, "name": "Transformer" }
]);

您缺少用于定义数组的方括号。

以下是您的代码的正确版本:

var http = require('http');
var express = require('express');

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

var port = 1337;

var app = express();

app.use(bodyParser.urlencoded({
    extended: true
}));


app.get('/api/list', function (request, response) {
    response.status(200).json([
        { "movieId": 1, "name": "The Pacific Rim" },
        { "movieId": 2, "name": "Transformer" }
    ]);
});

app.listen(port);