[英]Sending data from NodeJS without re-rendering the whole page?
我编写了一个非常简单的Express NodeJS应用程序,它从表单中的用户读取数据并发送到服务器。 服务器执行一些操作并将新字符串返回到同一页面。 但是,为了将新数据返回到当前加载的页面,我必须重新呈现页面。 我想通过从节点js发送字符串来更新字符串,而不是重新呈现整个页面。
我有以下问题:
为什么使用Post
方法发送数据,在req.body.XXX
提供数据但是使用Get
方法发送数据,为req.body.XXX
返回undefined
。
<html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <form id="myForm" action = "http://localhost:3000/testing" method="post"> Enter Url: <input type="text" name="urlEditText"/> <br /> <br /> Shortened Url:<%= shortenedUrl %> <br /> <br /> <input id="myButton" type="button" value="Submit" /> </form> </body> </html>
index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express', shortenedUrl: ''});
console.log("hello inside index.js method 0");
});
// passing an updated string back to the page
router.post('/yolo', function(req, res, next) {
res.render('index', { title: 'NewTitle', shortenedUrl: req.body.urlEditText});
console.log("hello inside index.js method 1");
});
编辑:
用于提交的JQuery脚本:
$(document).ready(function() {
$("#myButton").bind('click', function() {
event.preventDefault();
$("#myForm").submit(function() {
document.write("button clicked calling yolo script");
});
$.post('/yolo', function() {
document.write("button clicked calling yolo script");
alert("yolo");
});
});
我建议使用像socket.io这样的东西,这样你就可以从服务器发送和接收数据,而无需重新加载页面。 以下是他们网站的一个简单示例:
服务器(app.js)
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
客户端(index.html)
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
res.render
仅用于呈现页面。 在你的情况下,你很可能需要res.json({title: 'newTitle', ...})
至于你的第二个问题, req.body
只填充了POST
和PUT
请求的数据。 对于GET
您可以依赖req.query
或req.params
具体取决于您组织API路线的方式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.