如果呼叫不是来自表单中的提交方法,则Express'render / redirect不起作用 [英] Express' render/redirect does not work if the call isn't coming from a submit method in a form
问题描述
任务
从JS方法执行POST请求,以便将变量值作为参数发送。
环境
- NodeJS
- Express
- BodyParser
- ejs
我的第一次尝试
前端
< html>
< head>
< script src ='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'>< / script>
< script type =text / javascript>
function postAnswer(){
$ .post('vote',{message:hello!},function(returnedData){
console.log(Post returned data:+ returnedData);
});
}
< / script>
< / head>
< body>
< button id ='send'onClick ='postAnswer()'class ='btn btn-success btn-xs'> Svara< / button>
< / body>
< / html>
Server.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser());
require('./ app / routes.js')(app);
app.set('view engine','ejs');
app.use('/ public',express.static(__ dirname +'/ public'));
var server = require('http')。createServer(app);
server.listen(8080);
console.log('8080端口上的服务器...');
routes.js:
module.exports = function(app){
app.get('/',function(req,res){
res.render 'vote.ejs',{
message:''
});
});
app.post('/ vote',function(req,res){
var msg = req.body.message;
console.log(Got POST request with消息:+ msg;
res.render('index.ejs',{
message:''
});
});
};
结果:
不能呈现新页面。然而,它将返回返回数据参数中的整个'index.ejs'文件。
服务器: p>
客户端
第二次尝试:
< HTML>
< head>
< script src ='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'>< / script>
< script type =text / javascript>
function postAnswer(){
$ .post('vote',{message:hello!},function(returnedData){
console.log(Post returned data:+ returnedData);
});
返回false;
}
< / script>
< / head>
< body>
< form action ='/ vote'method ='post'>
< button id ='send'type ='submit'onsubmit ='return postAnswer()'class ='btn btn-success btn-xs'> Svara< / button>
< / form>
< / body>
< / html>
结果:
但是这不是一个非常干净的解决方案。
我的问题:
- 为什么第一次尝试工作?
- 如何将变量作为参数发送到具有良好干净解决方案的POST请求?
我不是一个jQuery专家,但我认为第一次尝试不起作用,因为 $。post
提供了一个AJAX请求,就像在单页应用中与后台的API进行交互的一样。
您的第二个示例提交表单,这是一个执行导航操作的浏览器操作(由表单的方法
属性指定)。在这种情况下,您在jQuery中添加的事件侦听器是多余的,应该被删除 - 它正在使另一个背景 POST
请求,在表单提交之前
对于您的第二个问题,提交表单提交的其他变量的方式(假设你实际上想做导航表单提交而不是针对API的XHR后台请求)是使用< input type =hidden>
元素。
所以,总结一下,为了做你在问题上描述的内容,你的例子HTML应该像这样(减去评论):
<!DOCTYPE html> <! - 只有您可以防止怪癖模式 - >
< html>
< head>
< meta charset =UTF-8> <! - (つ◕_◕)つ给UNICODE - >
< / head>
< body>
< form action ='/ vote'method ='post'>
< input type =hiddenname =messagevalue =hello!>
< button id ='send'type ='submit'class ='btn btn-success btn-xs'> Svara< / button>
< / form>
< / body>
< / html>
Task
Perform a POST request from a JS method, so that variable values can be sent as parameters.
Environment
- NodeJS
- Express
- BodyParser
- ejs
My first attempt
Frontend:
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
<script type="text/javascript">
function postAnswer() {
$.post('vote', { message: "hello!"}, function(returnedData) {
console.log("Post returned data: " + returnedData);
});
}
</script>
</head>
<body>
<button id='send' onClick='postAnswer()' class='btn btn-success btn-xs'>Svara</button>
</body>
</html>
Server.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser());
require('./app/routes.js')(app);
app.set('view engine', 'ejs');
app.use('/public', express.static(__dirname + '/public'));
var server = require('http').createServer(app);
server.listen(8080);
console.log('Server running on port 8080...');
routes.js:
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('vote.ejs', {
message: ''
});
});
app.post('/vote', function(req, res) {
var msg = req.body.message;
console.log("Got POST request with message: " + msg);
res.render('index.ejs', {
message: ''
});
});
};
Result:
The render method won't render a new page. It will however return the entire 'index.ejs' file in the returnedData parameter.
Server:
Client:
Second attempt:
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'></script>
<script type="text/javascript">
function postAnswer() {
$.post('vote', { message: "hello!"}, function(returnedData) {
console.log("Post returned data: " + returnedData);
});
return false;
}
</script>
</head>
<body>
<form action='/vote' method='post'>
<button id='send' type='submit' onsubmit='return postAnswer()' class='btn btn-success btn-xs'>Svara</button>
</form>
</body>
</html>
Result:
This does work, but it's not a very clean solution.
My questions:
- Why doesn't the first attempt work?
- How can I send variables as parameters to a POST request with a nice clean solution?
I'm not a jQuery expert, but I think the first attempt doesn't work because $.post
makes an AJAX request, the same way as you would in a single-page app to interact with an API in the background.
Your second example submits a form, which is an in-browser action that performs a navigation action (as specified by the method
attribute of the form). In this case, the event listener you add in jQuery is redundant, and should be removed - it's making another background POST
request, before the form submits the content of its fields in its request.
As for your second question, the way to submit additional variables with a form submission (presuming that you actually want to do a navigating form submission and not an XHR background request against an API) is to use <input type="hidden">
elements.
So, to summarize, to do what you're describing in your question, your example HTML should look like this (minus the comments):
<!DOCTYPE html> <!-- only you can prevent quirks mode -->
<html>
<head>
<meta charset="UTF-8"> <!-- ༼ つ ◕_◕ ༽つ Give UNICODE -->
</head>
<body>
<form action='/vote' method='post'>
<input type="hidden" name="message" value="hello!">
<button id='send' type='submit' class='btn btn-success btn-xs'>Svara</button>
</form>
</body>
</html>
这篇关于如果呼叫不是来自表单中的提交方法,则Express'render / redirect不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!