XMLHttpRequest和jQuery AJAX方法之间的响应头差异

时间:2018-03-22 21:28:32

标签: javascript php jquery node.js ajax

亲爱的,我的问题不重复。

代码:

var data = {'userId': window.cookie.get('userId'),
    'sessionId': window.cookie.get('sessionId')}

$.post(window.DbUrl + '/test', data, function (e) {
    console.log(e);
});

我尝试用jquery post发送ajax,响应是:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, Content-Type, X-Auth-Token, Authorization
Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:https://localhost:8080
Connection:keep-alive
Content-Length:1011
... 

代码:

var formdata = new FormData();
formdata.append('sessionId', window.cookie.get('sessionId'));
formdata.append('userId', window.cookie.get('userId'));
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", selff.myProgressHandler, false);
ajax.addEventListener("load", myCompleteHandler, false);
ajax.addEventListener("error", myErrorHandler, false);
ajax.addEventListener("abort", myAbortHandler, false);
ajax.open("POST", window.DbUrl + '/test',true);
ajax.send(formdata);

我在同一个URL响应中尝试使用XMLHttpRequest:

Allow:POST
Connection:keep-alive
Content-Length:4
Content-Type:text/html; charset=utf-8

在nodejs express服务器中,缺少Access-Control-Allow-*标题。

但是当ajax用XMLHttpRequest到php服务器时,每件事都是好的。

nodejs服务器:

app.post('/test', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', 'https://localhost:8080');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization');
    res.end('welcome');
});

php服务器还可以:

<?php
header('Access-Control-Allow-Origin: https://localhost:8080');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization');

?>wellcome

有什么问题?为什么php服务器都可以,nodojs都没有,为什么jquery ok在任何服务器上?

1 个答案:

答案 0 :(得分:1)

我不知道原因,但如果您想修复它,请使用cors包。 因为包在快递请求上有触发,所以在发送手册之前发送标题。