2

Description:

I'm trying to validate a <form> in the server side. To do this I send form inputs in JSON to the back-end (an express.js app) using AJAX. After validate, I send to the front-end another JSON with this structure:

{
     input1: true|false,
     ...
     inputN: true|false
}

(true is right and false wrong)

Now, in the front-end if one input it's wrong a <span> is added next to the <input> indicating that it's incorrect. If it's right happens the same but indicating that the <input> is correct.

The issue comes in back-end to front-end response, the AJAX call fails and IDK why.

HTML code:

<!DOCTYPE html>
<html>
<head>
    <script src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        function submitForm() {
            $('span').remove();

            let req = $.ajax({
                url: 'http:localhost:3000/validate',
                dataType: 'json',
                data: $('#myForm').serializeArray()
            });

            req.done((data, textStatus, jqXHR) => {
                alert('OK');

                for (input in data) {
                    let elem = '<span style="color: green">OK</span>';
                    if (!data[input])
                        elem = '<span style="color: red">ERROR</span>';
                    $('#${input}').append(elem);
                }
            });

            req.fail((jqXHR, textStatus, errorThrown) => {
                alert('ERROR');
            });
        }
    </script>
</head>
<body>
    <form id="myForm">
        <div id="name">
            <input type="text" name="name" placeholder="Name">
        </div>
        <div id="surname">
            <input type="text" name="surname" placeholder="Surname">
        </div>
        <input type="submit" onclick="submitForm()">
    </form>
</body>
</html>

Edited HTML code:

<!DOCTYPE html>
<html>
<body>
    <form id="myForm">
        <div id="name">
            <input type="text" name="name" placeholder="Name">
        </div>
        <div id="surname">
            <input type="text" name="surname" placeholder="Surname">
        </div>
        <input type="button" value="Send" onclick="submitForm()">
    </form>
    <script src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        function submitForm() {
            $('span').remove();

            let req = $.ajax({
                url: 'http:localhost:3000/validate',
                dataType: 'json',
                data: $('#myForm').serializeArray()
            });

            req.done((data, textStatus, jqXHR) => {
                alert('OK');

                for (input in data) {
                    let elem = '<span style="color: green">OK</span>';
                    if (!data[input])
                        elem = '<span style="color: red">ERROR</span>';
                    $('#${input}').append(elem);
                }
            });

            req.fail((jqXHR, textStatus, errorThrown) => {
                alert('ERROR');
            });
        }
    </script>
</body>
</html>

NodeJS code:

const express = require('express');


const app = express();

app.get('/validate', (req, res) => {
    let query = req.query;

    let obj = {};
    obj.name = query.name == 'Marco';
    obj.surname = query.surname == 'Canora';

    console.log(obj);

    res.json(obj);
});

app.listen(3000, () => {
    console.log('App is listening');
});

Browser console:

http://localhost:3000/validate?name=Marco&surname=Canora. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

BTW:

Using jsonpCallback seems to work but I don't understand how and why works.

jsonpCallback function not working

Marco Canora
  • 335
  • 2
  • 15

1 Answers1

1

Adding this to the app.js resolve's the issue:

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

https://enable-cors.org/server_expressjs.html

Ajax post response from express js keeps throwing error

Marco Canora
  • 335
  • 2
  • 15