[英]Not able to get response from NodeJs server express
Hello again everyone.再次大家好。 i am calling get method from front-end java-script whenever that page loads.
每当该页面加载时,我都会从前端 java 脚本调用 get 方法。 The problem is i am not getting the response of that get request in my web page JavaScript.
问题是我没有在我的网页 JavaScript 中得到该获取请求的响应。 I am calling the getChats method whenever chatroom.hbs loads to show all the existing chats in the chatroom to that user but it's seems like i am not getting the response from the server against that request.
每当 chatroom.hbs 加载以向该用户显示聊天室中的所有现有聊天时,我都会调用 getChats 方法,但似乎我没有从服务器获得针对该请求的响应。 These are the files in my project
这些是我项目中的文件
chatroom.js聊天室.js
var express = require('express');
var router = express.Router();
var obj = require('../bin/www');
var db = require('../databaseModels');
/* GET users listing. */
router.get('/:uName', function(req, res, next) {
res.render('chatroom', {title: 'Welcome to Chat Room', userName:
req.params.uName});
});
// save a new chat message in database
router.post("/putChats", async (req, res) => {
try {
var chat = new db.Chats(req.body)
await chat.save()
res.sendStatus(200)
//Emit the event
obj.io.emit("chat", req.body)
}
catch (error) {
res.sendStatus(500)
console.error(error)
}
})
// Get chat messages from detabase and return to client
router.get("/getChats", (req, res) => {
db.Chats.find({}, (error, chats) => {
res.send(chats)
})
})
// clear method for clearing the chats
router.post("/clear", function(){
// Remove all chats from collection
db.Chats.remove({}, function(){
obj.io.emit('cleared');
});
})
module.exports = router;
app.js应用程序.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require("body-parser");
var hbs = require('express-handlebars');
var indexRouter = require('./routes/index');
var chatroomRouter = require('./routes/chatroom');
var app = express();
// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/'}))
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
});
app.use('/', indexRouter);
app.use('/chatroom', chatroomRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
chatroom.hbs聊天室.hbs
<script>
var socket = io()
socket.connect('http://192.168.34.54:4747');
socket.on("chat", addChat)
$(() => {
getChats()
textarea.addEventListener('keydown', function(event){
if(event.which === 13 && event.shiftKey == false){
// Emit to server input
if( $('#username').val() != '')
{
var chatMessage = {
name: $("#username").val(), chat: $("#textarea").val()
}
postChat(chatMessage)
var obj = document.getElementById('textarea');
obj.value = '';
}
else{
alert('Plear enter name of the sender!!!!');
}
}
})
})
function postChat(chat) {
$.post("http://192.168.34.54:4747/chatroom/putChats", chat)
}
function getChats() {
$.get("http://192.168.34.54:4747/chatroom/getChats", (chats) => {
chats.forEach(addChat)
})
}
function addChat(chatObj) {
var message = document.getElementById('messages');
message.value += "\n" + chatObj.name+": "+chatObj.chat;
}
socket.on('cleared', function(){
var message = document.getElementById('messages');
message.value = '';
});
// Handle Chat Clear
clear.addEventListener('click', function(){
$.post("http://192.168.34.54:4747/chatroom/clear")
});
function myFunction() {
// Get the snackbar DIV
var x = document.getElementById("snackbar");
// Add the "show" class to DIV
x.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
(function($) {
$(document).ready(function() {
myFunction();
});
})(jQuery);
</script>
Never Mind I found the mistake :)没关系,我发现了错误:)
<script>
var socket = io()
socket.on("chat", addChat)
$(() => {
getChats()
textarea.addEventListener('keydown', function(event){
if(event.which === 13 && event.shiftKey == false){
// Emit to server input
if( $('#username').val() != '')
{
var chatMessage = {
name: $("#username").val(), chat: $("#textarea").val()
}
postChat(chatMessage)
var obj = document.getElementById('textarea');
obj.value = '';
}
else{
alert('Plear enter name of the sender!!!!');
}
}
})
})
function postChat(chat) {
$.post("http://192.168.34.54:3111/chats", chat)
}
function getChats() {
$.get("/chats", (chats) => {
chats.forEach(addChat)
})
}
function addChat(chatObj) {
var message = document.getElementById('messages');
message.value += "\n" + chatObj.name+": "+chatObj.chat;
}
socket.on('cleared', function(){
var message = document.getElementById('messages');
message.value = '';
});
// Handle Chat Clear
clear.addEventListener('click', function(){
$.post("http://192.168.34.54:3111/clear")
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.