我有一个简单的 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");
我有两个问题。
- 我是否正确地将表单中提取的数据发送到服务器?我可以在控制台中看到这些值,但网页一直在加载。我只想发送数据、显示和提醒,并保持在同一个页面中,并清理表单字段。
- 我应该在将数据发送到服务器之前或之后验证表单中的数据(以及如何验证)吗?例如,确保字段名称中没有插入数字,或者字段名称的长度应少于 30 个字符。
更新:我使用 Ajax 而不是我最初的方法将数据发送到服务器。我可以在控制台中看到使用 ajax 发送的信息,但不会触发 ajax 成功处理程序。我收到此错误 XMLHttpRequest 无法加载 http://localhost:3000/test。请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问 Origin 'null'。
提前致谢!
最佳答案
浏览器正在等待您的服务器的响应。尝试:
app.post('/formdata', function(req, res) {
console.log("You sent the name " + req.body.name + " and the address " + req.body.address);
res.send("ok");
});
至于验证,通常您希望同时验证客户端和服务器端的值。你可以使用类似 this 的东西如果你想坚持用 express ,或者看here或 here对于双重解决方案。
ajax 的更新:
您的代码中有一些错误。
1) “成功” Hook 中的错字(您输入的是“成功”)
2) 你打电话的方式sendFormData()
功能,您发送ajax请求并同时提交表单。拦截表单提交,或更改 <input type="submit"
进入<input type="button"
(所以它不会触发表单提交)
至于错误,您只能将 ajax 发送到最初为该页面提供服务的同一服务器(无需额外的努力)。这称为“same origin policy”。
在您的情况下,您似乎是使用"file"协议(protocol)直接从磁盘打开页面(浏览器中的 url 以 file://
开头)。您需要让真正的服务器为您的 html 提供服务,然后设置“相同的内容来源” header ,或者回发到同一服务器上的路径(没有 http://blabla...
部分)。
要使它正常工作,您可以做的最简单的事情是:
1) 让 Node 服务于您的静态内容(在本例中为 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/
在您的浏览器中
关于javascript - Node.js - 将数据发送到 Node.js 并以 HTML 形式验证插入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400298/