Access-Control-Allow-Origin 및 Angular.js $http
웹 앱을 만들 때 CORS 문제가 생기면 커피를 만들기 시작합니다.한동안 일을 망친 후에야 겨우 작동시킬 수 있었지만 이번에는 그렇지 않아서 도움이 필요해요.
클라이언트측 코드는 다음과 같습니다.
$http({method: 'GET', url: 'http://localhost:3000/api/symbol/junk',
headers:{
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
'X-Random-Shit':'123123123'
}})
.success(function(d){ console.log( "yay" ); })
.error(function(d){ console.log( "nope" ); });
서버 측은 Express 앱을 사용하는 일반 node.js입니다.코르스라는 익스텐션이 있는데 익스프레스에서 다음과 같이 사용되고 있습니다.
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
app.use(cors({origin:"*"}));
});
app.listen(3000);
app.get('/', function(req, res){
res.end("ok");
});
내가 하면
curl -v -H "Origin: https://github.com" http://localhost:3000/
다음과 같이 반환됩니다.
* Adding handle: conn: 0x7ff991800000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7ff991800000) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 3000 (#0)
* Trying ::1...
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:3000
> Accept: */*
> Origin: https://github.com
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Date: Tue, 24 Dec 2013 03:23:40 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
ok
클라이언트측 코드를 실행하면, 다음의 에러가 발생합니다.
OPTIONS http://localhost:3000/api/symbol/junk No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. angular.js:7889
XMLHttpRequest cannot load http://localhost:3000/api/symbol/junk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. localhost/:1
nope
Chromes 헤더 확인 중:
Request URL:http://localhost:3000/api/symbol/junk
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,es;q=0.6,pt;q=0.4
Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-methods, access-control-allow-headers, x-random-shit
Access-Control-Request-Method:GET
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:8000
Referer:http://localhost:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Response Headersview source
Allow:GET
Connection:keep-alive
Content-Length:3
Content-Type:text/html; charset=utf-8
Date:Tue, 24 Dec 2013 03:27:45 GMT
X-Powered-By:Express
요청 헤더를 확인해보니 테스트 문자열 X-Random-Shit이 "Access-Control-Request-Headers"에 있지만 값이 없습니다.또, 머릿속에서는, 설정하는 각 헤더에 대해서, blob이 아니고, 1 행씩의 행이 표시되는 것을 상정하고 있었습니다.
갱신 ---
프런트엔드를 Angular가 아닌 jQuery로 변경하고 백엔드를 다음과 같이 만들었습니다.
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
});
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
if ('OPTIONS' == req.method){
return res.send(200);
}
next();
});
app.get('/', function(req, res){
res.end("ok");
});
현재는 GET에서는 동작하지만, 그 이외에서는 동작하지 않습니다(PUT, POST..).
해결 방법이 있는지 알아보겠습니다.한편, RESTful의 컨셉을 배제하고, GETs로 모든 것을 만들고 있습니다.
Angular는 처음입니다.JS와 나는 이 CORS 문제에 부딪혔어, 거의 제정신이 아니었어!운 좋게도 이걸 고칠 방법을 찾았어.자, 갑니다...
문제는 AngularJS $resource를 사용하여 API 요청을 전송하면 이 오류 메시지가 뜬다는 것입니다.XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
네, 이미 콜백을 추가했습니다="JSON_CALLBACK"로 동작하지 않았습니다.
문제를 해결하기 위해 GET 방식을 사용하거나 $http를 사용하는 대신 실행한 작업입니다.GET Method를 JSONP로 대체하고 API 응답 형식도 JSONP로 변경합니다.
myApp.factory('myFactory', ['$resource', function($resource) {
return $resource( 'http://website.com/api/:apiMethod',
{ callback: "JSON_CALLBACK", format:'jsonp' },
{
method1: {
method: 'JSONP',
params: {
apiMethod: 'hello world'
}
},
method2: {
method: 'JSONP',
params: {
apiMethod: 'hey ho!'
}
}
} );
}]);
누가 도움이 됐으면 좋겠어요.:)
익스프레스 및 편집에 성공했습니다.res.header
내 거랑 네 거랑 꽤 비슷하지만 다른 게 있어Allow-Headers
이하에 기술한 바와 같이
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
또한 Angular와 Node/Express를 사용하지만 Angular 코드에는 노드/Express만 호출된 헤더가 없습니다.
이 미들웨어를 쓰는 것이 도움이 될 수 있습니다!
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
자세한 것은, http://enable-cors.org/server_expressjs.html 를 참조해 주세요.
아래를 server.js에 추가하여 해결했습니다.
server.post('/your-rest-endpt/*', function(req,res){
console.log('');
console.log('req.url: '+req.url);
console.log('req.headers: ');
console.dir(req.headers);
console.log('req.body: ');
console.dir(req.body);
var options = {
host: 'restAPI-IP' + ':' + '8080'
, protocol: 'http'
, pathname: 'your-rest-endpt/'
};
console.log('options: ');
console.dir(options);
var reqUrl = url.format(options);
console.log("Forward URL: "+reqUrl);
var parsedUrl = url.parse(req.url, true);
console.log('parsedUrl: ');
console.dir(parsedUrl);
var queryParams = parsedUrl.query;
var path = parsedUrl.path;
var substr = path.substring(path.lastIndexOf("rest/"));
console.log('substr: ');
console.dir(substr);
reqUrl += substr;
console.log("Final Forward URL: "+reqUrl);
var newHeaders = {
};
//Deep-copy it, clone it, but not point to me in shallow way...
for (var headerKey in req.headers) {
newHeaders[headerKey] = req.headers[headerKey];
};
var newBody = (req.body == null || req.body == undefined ? {} : req.body);
if (newHeaders['Content-type'] == null
|| newHeaders['Content-type'] == undefined) {
newHeaders['Content-type'] = 'application/json';
newBody = JSON.stringify(newBody);
}
var requestOptions = {
headers: {
'Content-type': 'application/json'
}
,body: newBody
,method: 'POST'
};
console.log("server.js : routes to URL : "+ reqUrl);
request(reqUrl, requestOptions, function(error, response, body){
if(error) {
console.log('The error from Tomcat is --> ' + error.toString());
console.dir(error);
//return false;
}
if (response.statusCode != null
&& response.statusCode != undefined
&& response.headers != null
&& response.headers != undefined) {
res.writeHead(response.statusCode, response.headers);
} else {
//404 Not Found
res.writeHead(404);
}
if (body != null
&& body != undefined) {
res.write(body);
}
res.end();
});
});
@ 스와프닐 니와네
저는 Ajax 요청을 호출하여 데이터를 jsonp로 포맷함으로써 이 문제를 해결할 수 있었습니다.
$.ajax({
method: 'GET',
url: url,
defaultHeaders: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
'Accept': 'application/json'
},
dataType: 'jsonp',
success: function (response) {
console.log("success ");
console.log(response);
},
error: function (xhr) {
console.log("error ");
console.log(xhr);
}
});
a i i용 i i i i 。JSONP
in the method in the method in 。$http
및 params
뭇매를 맞다
params = {
'a': b,
'callback': 'JSON_CALLBACK'
};
$http({
url: url,
method: 'JSONP',
params: params
})
다음을 사용해 보십시오.
$.ajax({
type: 'POST',
url: URL,
defaultHeaders: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
'Accept': 'application/json'
},
data: obj,
dataType: 'json',
success: function (response) {
// BindTableData();
console.log("success ");
alert(response);
},
error: function (xhr) {
console.log("error ");
console.log(xhr);
}
});
언급URL : https://stackoverflow.com/questions/20754489/access-control-allow-origin-and-angular-js-http
'programing' 카테고리의 다른 글
Oracle SQL Developer 실행 설명 계획 결과 이해 (0) | 2023.04.03 |
---|---|
python에서 wordpress REST api를 사용하여 이미지를 업로드하는 방법은 무엇입니까? (0) | 2023.04.03 |
springboot 2.3.5로부터의 업그레이드.2.4.1로 릴리즈 - ClassNotFoundException: org.springframework.boot.context.properties.Configuration Bean Factory Metadata (0) | 2023.04.03 |
로컬 속편 설정에 환경 변수 사용 (0) | 2023.04.03 |
숫자와 범위가 있는 루프용 AngularJS (0) | 2023.04.03 |