简体   繁体   中英

Node.js How to pass Ajax success message to app.js

Node.js how to pass Ajax success message to app.js , because i need to know user Log-in status

ex:If user have not logged in, redirect to log-in.html , so I need to know success message.

index.html

...
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript>

            $.ajax({
                url: URLs,
                data: $('#sentToBack').serialize(),
                type:"POST",
                dataType:'text',

                success: function(msg){
                   if(msg == "True")
                   {
                     location.href = '/index.html';
                   }

                },

                 error:function(msg){ 
                    console.log(msg);
                 }
            });

</script>

app.js

var express = require('express');
var app = express();

app.get('/', function(req, res){
  // I want to send to here !!
});

app.listen(3000);

There are many different ways to do this.

This here

app.get('/', function(req, res){
  // I want to send to here !!
});

is defining the function that will handle get requests to your root route .

If you are sending AJAX requests, you need to think about what METHOD (GET/POST/PUT/DELETE) you are using, and what CONTENT you are sending. You may need something to parse the body if you are, for example, using JSON.

If you want to maintain session information and logins etc, I would suggest looking into some middleware like PassportJS .

You can configure Passport to automatically redirect to the login page whenever a request is received from an unauthenticated user.

you have to declare a post ressource with express and enable the body parser

app.use(express.bodyParser());
app.post('/yourRessource', function(req, res) {
  var sendToBack = req.body;
  console.log(sendToBack); // debugging
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM