使用nodejs实现页面跳转

使用NodeJs实现页面的跳转

1 创建testApp.js:

var http=require('http');
var fs=require('fs');
var server =http.createServer();
server.listen(8080,function(){
	console.log("Server is rining port 8080");
});
//请求回调函数
var handRequest=function (req,res){
	console.log('当前的请求是:'+req.url);
//	response.write('hello');
//	response.write('world');
	//response.writeHead(响应状态码,响应头对象)
	var url=req.url;
	if(url=="/login"){
		res.writeHead(200,{
			'Content-Type':'text/html'
		});
		fs.readFile('index.html','utf8',function(err,data){
			if(err){
				throw err;
			}
			res.end(data);
		});
	}else{
		res.writeHead(200,{
			'Content-Type':'text/html'
		});
		fs.readFile('404.html','utf8',function(err,data){
			if(err){
				throw err;
			}
			res.end(data);
		});
	}
	//发送完数据后结束响应
	//res.end('404 NotFound');
};
//任何请求都会触发该事件
server.on('request',handRequest);

2 创建index.html和404.html

最后运行testApp.js,命令 node testApp.js:

成功界面:




  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在前端登陆界面登陆成功后,需要向后端发送请求,验证用户身份,如果身份验证成功,后端应该返回一个包含用户信息的 token 或者 session,前端将这个 token 存储在浏览器的 cookie 或者 localStorage 中,并携带这个 token 跳转到首页。 在 nodejs 中,可以使用 Express 框架来实现跳转到首页,代码如下: ```javascript const express = require('express'); const app = express(); // 处理登陆请求 app.post('/login', (req, res) => { // 验证用户身份,生成 token const token = generateToken(); // 将 token 存储在 cookie 或者 localStorage 中 res.cookie('token', token); // 跳转到首页 res.redirect('/home'); }); // 首页路由 app.get('/home', (req, res) => { // 获取存储在 cookie 或者 localStorage 中的 token const token = req.cookies.token || req.query.token; // 验证 token 是否有效,如果有效,渲染首页页面 if (verifyToken(token)) { res.render('home'); } else { // 如果 token 无效,跳转到登陆页面 res.redirect('/login'); } }); // 启动服务器 app.listen(3000, () => { console.log('Server started on http://localhost:3000'); }); ``` 在这个例子中,我们使用了 express 的 `res.redirect()` 方法来实现跳转到首页。在首页路由中,我们首先获取存储在 cookie 或者 localStorage 中的 token,然后验证 token 是否有效,如果有效,渲染首页页面,如果无效,跳转到登陆页面。 需要注意的是,在生产环境中,必须对 token 进行加密和解密,以防止恶意用户伪造 token。可以使用 JWT(JSON Web Token)来实现 token 的加密和解密。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值