Nodejs 请求路由时 获得返回状态码 控制台显示是304 网页中显示是200

Nodejs 请求路由时 获得返回状态码 控制台显示是304 网页中显示是200

<script> function Connection(url,callback){ if (window.XMLHttpRequest){ var xmlhttp=new XMLHttpRequest(); } else{ var xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”); }
xmlhttp.onreadystatechange=function(){ if(xmlhttp.status==200) { callback(xmlhttp.status); } } xmlhttp.open(“GET”,url,true); xmlhttp.send(); }

	 function check(){
		Connection("http://localhost:3000/check",function(callback){
		 console.log(callback);
		})
	 }

setInterval("check()",3000);

</script>

/check code

router.get(’/check’,function(req,res){ fs.readFile(’./result.html’,function(err,data){ if(err) throw err; res.send(200,data.toString()); }) })

控制台显示 GET GET /check 304 2ms GET /check 304 1ms GET /check 304 1ms

网页中显示200 。。。 请问这是怎么回事 是否跟Python 一样 可以设置不允许重定向 返回304 就会返回304 不是重定向到200


6 回复

Node.js 请求路由时获得返回状态码

问题描述

在使用 Node.js 进行 HTTP 请求时,发现控制台输出的状态码为 304(Not Modified),但网页中显示的状态码却是 200(OK)。这似乎与预期不符,因为通常情况下,304 应该表示客户端缓存的数据是最新的,而无需重新请求服务器。

示例代码

首先,我们来看一下你的示例代码。这里使用了 XMLHttpRequest 对象来发送 HTTP 请求,并且在 onreadystatechange 回调函数中处理响应状态。

<script>
    function Connection(url, callback) {
        if (window.XMLHttpRequest) {
            var xmlhttp = new XMLHttpRequest();
        } else {
            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                callback(xmlhttp.status);
            }
        };
        
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    function check() {
        Connection("http://localhost:3000/check", function (status) {
            console.log(status);
        });
    }

    setInterval(check, 3000);
</script>

在服务器端,路由处理如下:

const express = require('express');
const fs = require('fs');
const app = express();

app.get('/check', (req, res) => {
    fs.readFile('./result.html', (err, data) => {
        if (err) throw err;
        res.send(200, data.toString());
    });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

问题分析

  1. HTTP 缓存机制

    • 当客户端请求资源时,如果资源的 Last-Modified 或 ETag 信息符合客户端缓存条件,则服务器会返回 304 状态码,指示客户端可以使用缓存中的数据。
    • 你可能已经设置了某些缓存策略,使得服务器返回 304 状态码。但是,客户端仍然会发起请求,并且在接收到 304 后,会根据缓存数据进行更新。
  2. 控制台 vs. 网页状态

    • 控制台中显示的是服务器返回的实际状态码(304)。
    • 网页中显示的是客户端最终使用的状态码(可能是 200,如果缓存数据有效)。

解决方案

如果你希望始终获取最新的数据,可以通过以下几种方式解决:

  1. 禁用缓存: 在发送请求时,可以添加一个随机参数或时间戳,以避免缓存的影响。

    function Connection(url, callback) {
        url += '?_=' + new Date().getTime(); // 添加时间戳
        if (window.XMLHttpRequest) {
            var xmlhttp = new XMLHttpRequest();
        } else {
            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                callback(xmlhttp.status);
            }
        };
        
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }
    
  2. 检查缓存策略: 如果你希望保持缓存策略,确保客户端正确处理 304 状态码,并从缓存中读取数据。

通过上述方法,你可以更好地理解并控制 Node.js 中的 HTTP 请求和缓存机制。


网页控制台里是重定向以后的页面的 200 吧, 确认下 url

标准有规定,如果服务器返回304,客户端浏览器在有缓存情况下可以视为200处理 手动setHeader If-None-Match或者If-Modified-Since就可以获取到真实状态码 这是刚才别人回答的。。。 可是 setHeader If-None-Match或者If-Modified-Since 头的值设成什么呢。。。。

res.send(200,data.toString()); 卧槽。你都指定了抛200出去。还问。

设置的200 控制台显示的是304 我设置了 If-Modified-Since = 0 后 每次控制台都返回 200了

这个问题涉及到HTTP缓存机制以及如何处理状态码。在你提供的代码中,浏览器可能因为缓存机制而发送了条件请求(如 If-Modified-SinceIf-None-Match),服务器返回 304 Not Modified 表明资源没有更新,但浏览器会使用本地缓存中的资源。

示例代码解释

你可以通过以下方式来确保Node.js服务器正确响应,并在客户端正确处理状态码:

服务器端代码 (server.js):

const express = require('express');
const fs = require('fs');

const app = express();

app.get('/check', (req, res) => {
    const filePath = './result.html';
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.status(500).send('Internal Server Error');
        } else {
            res.set('Cache-Control', 'no-cache, no-store, must-revalidate'); // 防止缓存
            res.set('Pragma', 'no-cache');
            res.set('Expires', '0');
            res.send(data.toString());
        }
    });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

客户端JavaScript代码 (index.html):

<script>
function Connection(url, callback) {
    if (window.XMLHttpRequest) {
        var xmlhttp = new XMLHttpRequest();
    } else {
        var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback(xmlhttp.status, xmlhttp.responseText);
        } else if (xmlhttp.readyState == 4) {
            callback(xmlhttp.status);
        }
    };
    
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

function check() {
    Connection("http://localhost:3000/check", function(status, response) {
        console.log(status); // 在控制台输出状态码
        document.getElementById('status').innerText = status; // 在页面中显示状态码
    });
}

setInterval(check, 3000);
</script>

<div id="status">Status:</div>

解释

  1. 服务器端:

    • 使用 res.set('Cache-Control', 'no-cache, no-store, must-revalidate') 来防止缓存。
    • 设置其他缓存相关的头,如 PragmaExpires,以确保资源不会被缓存。
  2. 客户端:

    • Connection 函数中,检查 xmlhttp.status 并回调相应的状态码。
    • check 函数中,通过 document.getElementById('status').innerText = status; 更新页面中的状态码。

通过这些更改,你可以确保服务器和客户端正确处理状态码,并且可以清楚地看到 304 状态码而不是 200

回到顶部