使用机器IP访问localhost会导致Ajax调用失败

Accessing localhost with machine IP results in failing Ajax calls

本文关键字:Ajax 调用 失败 localhost 机器 IP 访问      更新时间:2023-09-26

Angular中的Ajax GET调用失败。

会引发以下错误:

XMLHttpRequest cannot load http://localhost:3000/learning_record_service/get_document?document_id=288. Origin http://127.0.0.1:3000 is not allowed by Access-Control-Allow-Origin. 

下面是请求的详细信息:

Request URL:http://localhost:3000/learning_record_service/get_document?document_id=288
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, x-requested-with
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:3000
Origin:http://127.0.0.1:3000
Referer:http://127.0.0.1:3000/documents/open/288?sc=c961d72844bbc5439923e097860057d0&angular=1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.22 (

下面是代码:

$http.get('/learning_record_service/get_document?document_id=' + document_id).success(function(data){
//success code
});

查看您的请求,我们可以看到以下内容:

Request URL:http://localhost:3000/learning_record_service/get_document?document_id=288
...
Host:localhost:3000
Origin:http://127.0.0.1:3000
Referer:http://127.0.0.1:3000/documents/open/288?sc=c961d72844bbc5439923e097860057d0&angular=1

正如你所看到的,有些东西导致你的代码混淆了localhost:3000127.0.0.1:3000。这将被解释为"跨域"或"跨域"请求,这是大多数浏览器默认不允许的。