【问题标题】:Post ajax request send a options request instead of a post发布 ajax 请求发送选项请求而不是帖子
【发布时间】:2017-06-08 09:31:56
【问题描述】:

我正在发送一个 post ajax 请求:

var responsehttpreq = {}
function createAndSendXmlHttpReq(){
    requestBody = {
        hostname: "prova",
        pathname: "prova",
        query: "prova",
        method: "prova"
    }
    console.log("Siamo nella funzione createAndSendXmlHttpReq")
    var req = new XMLHttpRequest()
    req.onreadystatechange = handler
    req.open("POST","http://localhost:8080",true)
    req.setRequestHeader("Content-type","application/json")
    req.send(JSON.stringify(requestBody))
}

function handler(){
    if(this.readyState == 4 && this.status == 200){
        console.log('----Risposta http------')
        console.log('Status Code:'+this.status)
        console.log('Dati:'+this.response)
        responsehttpreq = JSON.parse(this.response)
    }
}

从 html 页面中的按钮调用 createAndSendXmlHttpReq(),当我按下按钮时,我没有收到任何响应,但我可以从开发人员控制台看到已发送选项请求,用于 CORS 选项. 我已经实现了一个节点 js 服务器,如果选项请求发送正确的响应:

if(req.method == "OPTIONS"){
        res.setHeader("Access-Control-Allow-Origin","*")
        res.setHeader("Access-Control-Allow-Methods","POST")
        res.setHeader("Access-Control-Request-Headers","content-type")
        res.end()
    }

浏览器从服务器接收到选项请求的 200 ok 响应,但之后我的 ajax 发布请求不会到达服务器。 有什么问题?

【问题讨论】:

    标签: javascript node.js ajax


    【解决方案1】:
    res.setHeader("Access-Control-Allow-Origin","*")
    

    响应preflight OPTIONS requestAccess-Control-Allow-Origin 标头不能使用通配符。

    您的浏览器控制台应该会告诉您这一点。

    您需要查看Origin 请求标头,确定您是否可以接受,然后将其用作Access-Control-Allow-Origin 标头的值。

    【讨论】:

    • @Alexandru-Ionut Mihai — 我已经撤销了你的编辑。问题是阅读请求然后设置响应......我引用了问题中的代码。请勿编辑其他人的代码,格式除外。
    • 在我的选项请求的 Origin 标头中写有“null”,现在我的服务器正在发送 Access-Control-Allow-Origin: null,但是在服务器响应之后没有发布请求被触发:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2011-06-02
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多