Node.js – 将数据发送到Node.js,并以HTML格式validation插入的数据
我有一个简单的HTML表单
的index.html
<!DOCTYPE html> <html> <head> <title>My Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> function sendFormData(){ var formData = JSON.stringify($("#myForm").serializeArray()); $.ajax({ type: "POST", url:"http://localhost:3000/test", data: formData, sucess: function(){ alert("something!"); }, error: function(textstatus, errorThrown) { alert('text status ' + textstatus + ', err ' + errorThrown); } }); } </script> </head> <body> <form id="myForm"> Name: <input type="text" name="name"> Address: <input type="text" name="address"> <input type="submit" value="Submit" onClick="sendFormData()"> </form> </body> </html>
我正在使用Node.js将数据发送到服务器
server.js
// Dependencies var express = require('express'); var bodyParser = require('body-parser'); // Express var app = express(); app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json()); // Get information submitted app.post('/test', function(req, res) { console.log("Information received !"); console.log(req.body); res.send("Ok!"); }); // Start server app.listen(3000); console.log("API is running on port 3000");
我有两个问题。
- 我是否正确地将提取的数据从表单发送到服务器? 我可以看到控制台中的值,但网页不断加载。 我只是想发送数据,显示和提醒,并留在同一个页面与表格字段清理。
- 我应该在将数据发送到服务器之前还是之后validation数据(以及如何)? 例如,确保在字段名称中没有插入数字,或者字段名称长度小于30个字符。
更新:我用Ajax而不是我最初的方法发送数据到服务器。 我能够在控制台中看到与ajax一起发送的信息,但是ajax成功处理程序不会触发。 我得到这个错误XMLHttpRequest cannot load http://localhost:3000/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
XMLHttpRequest cannot load http://localhost:3000/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
提前致谢 !
浏览器正在等待服务器的响应。 尝试:
app.post('/formdata', function(req, res) { console.log("You sent the name " + req.body.name + " and the address " + req.body.address); res.send("ok"); });
至于validation,通常你会想validation客户端和服务器端的值。 如果你想坚持快递,你可以使用这样的东西,或者在这里或这里看到一个双重解决scheme。
更新ajax的东西:
你的代码有一些错误。
1)“成功”的错字(你input'成功')
2)你调用sendFormData()
函数的方式,你同时发送一个sendFormData()
请求并提交表单。 要么拦截表单提交,要么将<input type="submit"
更改为<input type="button"
(所以不会触发表单提交)
至于错误,你只能发送一个Ajax到最初服务页面的服务器(没有额外的努力)。 这被称为“ 同源政策 ”。
在你的情况下,它看起来像直接从磁盘使用“文件”协议打开页面(浏览器中的URL以file://
开头)。 你需要有一个真正的服务器提供你的html,然后设置'相同的内容来源'头,或回发到同一服务器上的path(没有http://blabla...
部分)。
要做到这一点,最简单的方法是:
1)让节点提供你的静态内容(在这种情况下是index.html)
app.use(bodyParser.json()); app.use(express.static('public'));
2)将index.html移动到'public'目录,以便您的文件结构是:
- sever.js - [public] |- index.html
3)从您的请求中删除硬编码的url
$.ajax({ type: "POST", url:"/test", data: formData, //... });
4)在浏览器中打开http://localhost:3000/