简体   繁体   English

Node.js如何将Ajax成功消息传递给app.js

[英]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 Node.js如何将Ajax成功消息传递给app.js ,因为我需要知道用户登录状态

ex:If user have not logged in, redirect to log-in.html , so I need to know success message. 例如:如果用户尚未登录,请重定向到log-in.html ,所以我需要知道成功消息。

index.html 的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 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. 如果要发送AJAX请求,则需要考虑使用的是哪种方法(GET / POST / PUT / DELETE),以及要发送的内容。 You may need something to parse the body if you are, for example, using JSON. 例如,如果使用JSON,则可能需要一些内容来解析正文。

If you want to maintain session information and logins etc, I would suggest looking into some middleware like PassportJS . 如果您想维护会话信息和登录名等,我建议您研究一下PassportJS之类的 中间件

You can configure Passport to automatically redirect to the login page whenever a request is received from an unauthenticated user. 您可以将Passport配置为在收到未经身份验证的用户的请求时自动重定向到登录页面。

you have to declare a post ressource with express and enable the body parser 您必须使用express声明后期资源并启用正文解析器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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