gpt4 book ai didi

javascript - 无法在 Express 上的 NodeJS 服务器中发布参数 id

转载 作者:行者123 更新时间:2023-12-02 14:55:36 25 4
gpt4 key购买 nike

我目前正在开发一个 Ionic 应用程序,并使用 Express 在 NodeJS 中编写服务器并将其托管在 Heroku 上。但是,它没有正确发布所需的路线。当我在 Chrome 上测试时出现此错误:

Failed to load resource: the server responded with a status of 404 (Not Found) https://[SERVER NAME].herokuapp.com/rooms//messages

服务器应该在/rooms/和/messages/之间发布 id 参数,但事实并非如此。这是服务器端代码:

     var messages = []; //make an array to hold messages
var rooms = [];

app.get('/rooms', function(req, res) {
res.json(rooms);
});

app.get('/rooms/:id/', function(req, res){
var room = rooms[req.params.id];
res.json(room);
});

app.post('/rooms', function(req, res) {
var newRoom = {
timestamp: new Date()
//username: req.body.username
};
rooms.push(newRoom);
res.json(rooms);
console.log(rooms);
});



app.get('/messages', function(req, res) { //req = request, res = response
res.json(messages);
});

app.get('/messages/:id', function(req,res) {
var message = messages[req.params.id];
res.json(message);
});

app.post('/messages', function(req,res){
var newMessage = {
message:req.body.message,
username:req.body.username,
timestamp: new Date()
};

messages.push(newMessage);
res.json(messages);
});

为什么它没有正确发布正确的路线?当我检查 Heroku 上的日志时,它似乎没有获取房间的 :id。谢谢。

编辑:以下是 github 存储库以供进一步引用:客户:https://github.com/dukeeagle/ttt-client服务器:https://github.com/dukeeagle/ttt-server

最佳答案

我修好了!以下是正确的路由方法,有兴趣的 friend 可以引用一下:

app.get('/rooms', function(req, res) {  //req = request, res = response
var user = users[req.params.id];
var userRooms=[];

res.json(rooms);
});

app.get('/rooms/:id', function(req,res) {
var room = rooms[req.params.id];
res.json(room);
});

app.post('/rooms', function(req,res){
var newRoom = {
name:req.body.name,
id:rooms.length,
username:req.body.username,
timestamp: new Date(),
messages: [],
players: []
};
rooms.push(newRoom);
res.json(rooms);
});

app.post('/rooms/:id/messages', function(req, res){
var room = rooms[req.params.id];
var newMessage = {
username:req.body.username,
timestamp: new Date(),
message: req.body.message
}
room.messages.push(newMessage);
res.json(room);
});

app.post('/rooms/:id/players', function(req, res){
var room = rooms[req.params.id];
var newPlayer = {
timestamp: new Date(),
player: req.body.username
};
room.players.push(newPlayer);
res.json(room);
});

关于javascript - 无法在 Express 上的 NodeJS 服务器中发布参数 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35833564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com