当前,我想显示来自特定比赛帖子ID的聊天消息,这是我的操作方式,但是我没有设法根据比赛帖子ID来显示它。我有什么想念的吗?还是因为我的路线是/ chat,所以没有通过特定比赛帖子的req.params.id?
更新(聊天端点)
app.get('/chat', function(req, res){
Tournament.findById(req.params.id, function(err, tournament){
Message.find({tournament:req.params.id}, function(err, messages){
res.send(messages)
})
})
});
app.post('/chat', function(req, res){
let message = new Message(req.body)
message.save((err)=>{
if(err){
res.sendStatus(500);
}
else{
io.emit('message', req.body)
res.sendStatus(200)
}
})
})
(jquery)
$(()=>{
const socket = io()
$('#send').click(()=>{
let message = {
tournament: $('#tournament').val(),
name: $('#name').val(),
message: $('#message').val()
}
postMessage(message)
})
getMessages()
socket.on('message', addMessage)
function addMessage(message){
$('#messages').append(`<div class='container-chat'><div id='container-inline'><h6>${message.name}:</h6> <p>${message.message}</p></div></div>`)
}
function getMessages(){
$.get('http://localhost:3000/chat', (data)=>{
data.forEach(addMessage);
})
}
function postMessage(message){
$.post('http://localhost:3000/chat', message)
}
})
(tournament.pug)
input#tournament.form-control.input-sm.chat_input(type='hidden', placeholder='Tournament Id', value=tournament._id)
input#name.form-control.input-sm.chat_input(type='hidden', placeholder='User Username', value=user.username)
span.input-group-btn
input#message.form-control.input-sm.chat_input(type='text', placeholder='Type message')
span.input-group-btn
button#send.btn.btn-outline-secondary.btn-sm Send
(MessageSchema)
let MessageSchema = mongoose.Schema({
tournament:{
type: String
},
name:{
type: String
},
message:{
type: String
},
date: { type: Date, default: Date.now }
});
答案 0 :(得分:0)
将脚本文件修改为以下内容:您缺少正确的参数ID和url中的“ http”。
$(()=>{
const socket = io();
$('#send').click(()=>{
let message = {
tournament: $('#tournament').val(),
name: $('#name').val(),
message: $('#message').val()
}
postMessage(message)
})
getMessages()
socket.on('message', addMessage)
function addMessage(message){
$('#messages').append(`<div class='container-chat'><div id='container-inline'><h6>${message.name}:</h6> <p>${message.message}</p></div></div>`)
}
function getMessages(){
$.get('http://localhost:3000/chat' + $('#tournament').val(), (data)=>{
data.forEach(addMessage);
})
}
function postMessage(message){
$.post('http://localhost:3000/chat', message)
}
})