[英]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.