如果浏览器刷新节点,则更改URL

时间:2017-01-18 11:56:50

标签: javascript node.js refresh

我有一个节点应用。让我们说网址是这样的:

http://www.testurl.com/?access_token=1234。此网址由Spotify生成,因为此access_toke n需要使用其API。

只有当用户刷新页面时,我才希望网址删除网址的最后一部分并加载http://www.testurl.com。重要的是它只在页面刷新时发生,因此用户必须再次进行身份验证。

I have tried these js solutions,但它们都不起作用。我认为他们没有为原始海报工作,因为没有接受的答案。

我已经看到detect browser refresh using php有可能。有谁知道是否可以使用node来检测等效物?

php解决方案看起来像这样

$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

我也试过以下,但也没有用。

window.onbeforeunload = function(event){
    window.location.href = 'http://www.google.com';
};

2 个答案:

答案 0 :(得分:0)

为什么不在页面加载时将其从网址中删除,以便在页面刷新时它就消失了?

history.replaceState(null, '', location.pathname);

答案 1 :(得分:0)

不知道这是否是解决您尝试做的任何事情的最佳方法,但可以通过访问request.headers对象来检查Node内部的HTTP标头。这是一个示例代码:

const http = require('http');
const url = require('url');

http.createServer(function(req, res) {
	res.writeHead(200, {
		'Content-Type': 'text/html'
	});

	// Home controller
	if(url.parse(req.url).path === "/") {

		if(req.headers["cache-control"] && req.headers["cache-control"] === "max-age=0") {
			console.log("User refreshed");
		} else {
			console.log("User did not refresh");
		}

		res.end("<h1>Hello there!</h1>");
	} else {
		res.statsCode = 404;
		res.end("Not found");
	}

}).listen(3000);