0

I have the following code:

 $("button").click(function() { 
      $.ajax({
         url: 'http://***.com:3000/login',
         data: {
            format: 'json',
            username: $('#username').val(),
            password: $('#password').val()
         },
         error: function() {
            console.log("error");
            alert('FAIL');
         },
         dataType: 'jsonp',
         success: function(data) {
            alert('OK');
            console.log("success");
         },
         type: 'GET'
      });


   })

The situation is that once I send a valid username and password and I see that the server code reaches the line:

        res.status(200).send("OK");

the moment the response returns to the client, the code enters the 'error' case.

The console of the browser shows:

Uncaught ReferenceError: OK is not defined

at <anonymous>:1:1

at p (jquery.min.js:2)

at Function.globalEval (jquery.min.js:2)

at text script (jquery.min.js:4)

at Nb (jquery.min.js:4)

at A (jquery.min.js:4)

at XMLHttpRequest.<anonymous> (jquery.min.js:4)

It's really odd because it doesn't point to any place in my code.

The network tab says: enter image description here It seems like instead of 200 HTTP code, I have 304.

Do you know why and how to fix it?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
CrazySynthax
  • 13,662
  • 34
  • 99
  • 183

3 Answers3

1

This is the solution:

$("button").click(function() { 
      $.ajax({
         url: 'http://bank-example.com:3000/login',
         async: false,
         data: JSON.stringify({
            username: $('#username').val(),
            password: $('#password').val()
         }),
         contentType: "application/json",
         Accept: 'application/json; charset=utf-8',
         type: 'POST'
      }).done(function(data) {
         alert('ok');
      }).fail(function(data){
         alert('fail');
      });
   })
CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
-1

HTML and Javascript.

    <!DOCTYPE html>
<html lang="en">

<head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <input type="text" name="author" value="" id="author">
    <input type="text" name="text" value="" id="text">

    <button type="submit" id="button"> Submit </button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
    <script>
        $("#button").click(function() {
            $.ajax({
                type: "POST",
                url: `http://localhost:4730/quote`,
                data: JSON.stringify({
                    author: $('#author').val(),
                    text: $('#text').val()
                }),
                dataType: "json",
                contentType: "application/json",
                Accept: 'application/json; charset=utf-8',
                success: function(data) {
                    console.log(data);
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    </script>
</body>

</html>

Node code

 var express = require('express');
    var app = express();
    app.use(express.bodyParser());
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });
    var quotes = [{
            author: 'Audrey Hepburn',
            text: "Nothing is impossible, the word itself says 'I'm possible'!"
        },
        {
            author: 'Walt Disney',
            text: "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"
        },
        {
            author: 'Unknown',
            text: "Even the greatest was once a beginner. Don't be afraid to take that first step."
        },
        {
            author: 'Neale Donald Walsch',
            text: "You are afraid to die, and you're afraid to live. What a way to exist."
        }
    ];
    app.get('/', function(req, res) {
        res.json(quotes);
    });

    app.post('/quote', function(req, res) {
        console.log(req.body.author)
        console.log(req.body.text)
        if (!req.body.hasOwnProperty('author') ||
            !req.body.hasOwnProperty('text')) {
            res.statusCode = 400;
            return res.send('Error 400: Post syntax incorrect');
        }

        let newQuote = {
            author: req.body.author,
            text: req.body.text
        }
        quotes.push(newQuote);
        res.json(true);
    })

    app.listen(process.env.PORT || 4730);
Mateen Kadwaikar
  • 403
  • 4
  • 17
-1

jsonp inserts code block

<script src='http://***.com:3000/login?...'>

in DOM for solving cross domain issue. When src attribute of script tag occurs a request to web server, response body is evaluated as javascript block. just that time, If responsed text block is can't evaluated as javascript. Browser occurs error.

https://en.wikipedia.org/wiki/JSONP