Node.js - 将数据发送到Node.js并以HTML格式验证插入的数据

时间:2015-04-01 20:36:43

标签: javascript node.js

我有一个简单的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");

我有两个问题。

  1. 我是否正确地将提取的数据从表单发送到服务器?我可以在控制台中看到值,但网页会继续加载。我只想发送数据,显示和提醒,并保持在同一页面,并清除表格字段。
  2. 我应该在将数据发送到服务器之前或之后验证表单中的数据(以及如何)吗?例如,确保字段名称中没有插入数字,或者字段名称长度应少于30个字符。
  3. 更新:我使用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.

    提前致谢!

1 个答案:

答案 0 :(得分:2)

浏览器正在等待服务器的响应。尝试:

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之类的内容,或者查看herehere以获得双重解决方案。

更新ajax的事情:

您的代码中有一些错误。

1)成功的错字&#39; hook(你键入&#39;成功&#39;)

2)你调用sendFormData()函数的方式,你们都发送ajax请求并同时提交表单。截取表单提交,或将<input type="submit"更改为<input type="button"(因此它不会触发表单提交)

对于错误,您只能将ajax发送到最初为页面提供服务的同一服务器(无需额外工作)。这被称为&#34; same origin policy&#34;。

在您的情况下,您似乎正在使用&#39;文件&#39;直接从磁盘打开页面。协议(浏览器中的网址以file://开头)。您需要有一个真实的服务器来提供您的HTML,然后设置相同的内容来源&#39;标题,或回发到同一服务器上的路径(没有http://blabla...部分)。

要使其发挥作用,最简单的方法是:

1)让节点提供静态内容(本例中为index.html)

app.use(bodyParser.json());
app.use(express.static('public'));

2)将index.html移入公众&#39;目录,以便您的文件结构是:

- sever.js
- [public]
    |- index.html

3)从您的请求中删除硬编码的网址

$.ajax({
    type: "POST",
    url:"/test",
    data: formData,
    //...
});

4)在浏览器中打开http://localhost:3000/