【发布时间】: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
【问题讨论】:
-
包含一些代码!
-
如果没有返回内容,服务器应该返回 HTTP 状态码 204(无内容)。有关详细信息,请参阅stackoverflow.com/a/46956926/441292。
-
这是 FF 错误:bugzilla.mozilla.org/show_bug.cgi?id=884693。解决方案如下:204 响应 (NO_CONTENT)
标签: javascript http firefox