Let_IT_roll
Let_IT_roll

Reputation: 399

Node.js - Send data to Node.js and validate inserted data in HTML form

I have a simple HTML form

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>

and I'm using Node.js to send the data to the server

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");

I have two questions.

  1. Am I sending the extracted data from the form to the server correctly ? I can see the values in the console but the webpage keeps loading. I just wanted to send the data, display and alert and stay in the same page with the forms field cleaned.
  2. Should i validate the data (and how) from the form before or after sending the data to the server ? For instance, make sure no numbers are inserted in the field name or the field name should be less than 30 characters long.

UPDATE: I used Ajax instead of my initial approach to send the data to the server. I'm able to see the information sent with ajax in the console but the ajax success handler does not fire. I get this error 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.

Thanks in advance !

Upvotes: 3

Views: 7207

Answers (1)

panta82
panta82

Reputation: 2721

Browser is waiting on the response from your server. Try:

app.post('/formdata', function(req, res) {
    console.log("You sent the name " + req.body.name + " and the address " + req.body.address);
    res.send("ok");
});

As for validation, usually you'd want to validate values both client side and server side. You can use something like this if you want to stick with express, or see here or here for a dual solution.

Update for the ajax thing:

You have a few errors in your code.

1) Typo in the 'success' hook (you typed 'sucess')

2) The way you call sendFormData() function, you both send ajax request and submit the form at the same time. Either intercept form submission, or change <input type="submit" into <input type="button" (so it doesn't trigger form submit)

As for the error, you can only send ajax to the same server that initially served the page (without some additional effort). This is called "same origin policy".

In your case, it looks like you're opening the page directly from disk using the 'file' protocol (url in the browser begins with file://). You need to have a real server serve your html, and then either set up 'same content origin' headers, or post back to the path on that same server (without the http://blabla... part).

The easiest thing you can do to get this to work is:

1) Let node serve your static content (index.html in this case)

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

2) Move index.html into the 'public' directory, so that your file structure is:

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

3) Remove hardcoded url from your requests

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

4) Open http://localhost:3000/ in your browser

Upvotes: 2

Related Questions