谷歌浏览器运行javascript,XMLHttpRequest()代码发送post请求失败,提示跨域访问被禁止,该如何解决?

用谷歌浏览器获取本机服务器的javascript+html代码
然后用这段代码发送post请求
发送函数如下

sendData: function(json) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open('POST', this.HOST + ":" + this.PORT, false);
        xmlHttp.onload = function() { this.receiveResponse(xmlHttp); }.bind(this);
        xmlHttp.onerror = function() { this.onError(xmlHttp) }.bind(this);
        var msg = JSON.stringify(json);
        xmlHttp.setRequestHeader('Content-length', msg.length);
        xmlHttp.setRequestHeader("Connection", "close");
        xmlHttp.send(msg);
    }

谷歌浏览器报错如下:


ocr.js:147 Refused to set unsafe header "Connection"
sendData @ ocr.js:147
train @ ocr.js:107
onclick @ (index):13
ocr.js:148 XMLHttpRequest cannot load localhost:8000. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
sendData @ ocr.js:148
train @ ocr.js:107
onclick @ (index):13
ocr.js:148 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'localhost:8000'.
    at Object.sendData (http://localhost:8000/ocr.js:148:17)
    at Object.train (http://localhost:8000/ocr.js:107:18)
    at HTMLInputElement.onclick (http://localhost:8000/:13:73)

148行就是这个xmlHttp.send(msg);了。萌新表示束手无策。是xmlhttprequest不适合谷歌浏览器?还是要用什么玄学解决跨域访问问题?求dalao分析一波,感激不尽

阅读 7.2k
2 个回答

嗯…不是很知道这个"本机服务器"是指什么,其实也没见过这种报错~不过既然题主说是跨域问题,那么,可以考虑CROS解决(需要浏览器支持,当然chrome是ok的)~其他方案个人认为都比这个来得繁琐

xmlHttp.setRequestHeader('Content-length', msg.length);
xmlHttp.setRequestHeader("Connection", "close");```
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题