Node.js:GET请求返回404 Not Found

时间:2015-05-01 13:18:02

标签: node.js rest express get

正在使用Node.js和Express创建REST API。服务器从localhost:xxxx开始,但localhost:xxxx/bits返回404未找到错误。

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

app.get('/bits', function(req, res) {
    console.log("Bits called");
});

app.get('/bits/:id', function(req, res) {
    console.log("Bits ID called");
});

app.listen(xxxx);
console.log('Listening on port xxxx.');

帮助?

1 个答案:

答案 0 :(得分:2)

我刚刚运行了你的代码,但用一个端口号替换xxxx。它对我来说很好。

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

app.get('/bits', function(req, res) {
    res.send([{name:'bit1'}, {name:'bit2'}]);
});

app.get('/bits/:id', function(req, res) {
    res.send({id:req.params.id, name: "The Name", description: "description"});
});

app.listen(8080);
console.log('Listening on port 8080.');

我也运行了一些curl命令以显示它正常工作。

[09:24 AM] jsloyer@Jeffs-MacBook-Pro [Downloads]>curl http://127.0.0.1:8080/bits
[{"name":"bit1"},{"name":"bit2"}]
[09:25 AM] jsloyer@Jeffs-MacBook-Pro [Downloads]>curl http://127.0.0.1:8080/bits/1
{"id":"1","name":"The Name","description":"description"}
[09:25 AM] jsloyer@Jeffs-MacBook-Pro [Downloads]>

另外here is整个Node.js git项目,包括它的源代码。

您可以点击下面的按钮进行部署,以便查看它的实际效果。

Deploy to Bluemix