【问题标题】:Firefox is parsing empty response payloadFirefox 正在解析空响应负载
【发布时间】:2017-02-27 17:28:22
【问题描述】:

我们正在使用以下标头发出 XHR 请求(我已经简化了一点):

POST http://localhost:9001/login

Host: localhost:9001
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=utf-8
Content-Length: 67

然后我们的服务器会这样响应(再次简化):

Status code: 200 OK

Cache-Control: no-cache, no-store
Connection: close
Content-Length: 0
Date: Mon, 27 Feb 2017 17:19:53 GMT
Server: WildFly/9
Set-Cookie: JSESSIONID=123; path=/

响应中没有有效负载。注意Content-Length: 0。但 Firefox 仍然尝试将其解析为 XML。并将以下错误输出到控制台:

XML Parsing Error: no root element found 
Location: http://localhost:9001/login 
Line Number 1, Column 1

注意,服务器不会发送content-type 标头。而根据RFC 7231,它只需要在有实际内容时发送content-type 标头。

那么这是 Firefox 中的错误还是我的研究有问题?

自己复制

我编写了一个小型服务器和客户端来重现该问题。

server.js(以node ./server.js开头):

const fs = require('fs'), http = require('http');
const server = http.createServer(function (request, response) {
    if (request.method === 'POST') {
        // send empty response
        response.end();
        return;
    }

    // send file content
    fs.readFile('.' + request.url, function (error, content) {
        response.writeHead(200, { 'Content-Type': request.url === '/index.html' ? 'text/html' : 'text/javascript' });
        response.end(content);
    });
}).listen(8080);

index.html

<script src="client.js"></script>

client.js

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/login');
xhr.send();

在 Firefox 中打开 URL http://localhost:8080/index.html 时,JavaScript 控制台会出现错误。

火狐浏览器版本 51.0.1

【问题讨论】:

标签: javascript http firefox


【解决方案1】:

响应中没有有效负载。注意内容长度:0

这意味着有一个有效负载,该有效负载的大小为 0 字节。将null"" 之间的区别视为字符串。当您想要等效于 null 时,您在此处拥有的等效于 ""

将状态代码设置为 204 而不是 200 以表明您没有发送实体(并删除内容类型,因为没有内容类型没有实体)。

(很长一段时间,Firefox 仍然会为这种情况记录错误,但幸运的是,这最终得到了修复。即使它确实记录了错误,它仍然会继续正确运行任何脚本。

【讨论】:

    【解决方案2】:

    从 POST 请求来看,您似乎正在使用 XHR/JS 发送请求。

    所以问题很可能出在处理结果的代码中。

    (另外,请求中的Content-Type不正确,application/json上没有charset参数)

    【讨论】:

    • 这是 Firefox 在接收到带有空正文的 HTTP 200 时的行为方式,无论处理代码如何。 HTTP 204 作为响应代码将避免这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多