SP'S SPARKING

[해결] Access to XMLHttpRequest 에러 본문

HAPPYHACKING/ERROR SOLVED

[해결] Access to XMLHttpRequest 에러

SPSP 2022. 7. 27. 11:57

에러 내용

발단

Register 구현하려고 POST 썼는데,

I tried to use POST for implementing the 'Register' feature, but

전개

"Access to XMLHttpRequest at 'http://localhost:3000/users/signup' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

에러가 떴다. 이것저것 찾아보다 

I got this error, so I had searching for that

힌트

header("Access-Control-Allow-Origin: http://localhost:4200");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

(https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe)

를 써야 한다고 한다. 어디에 이 코드에 적용해야 할지 잘 모르겠다.

 

It said I need to put this code, but I wasn't sure which line should I put this code line

 

그래서 GitHub에 이 코드를 쓴 프로젝트를 찾아봤다.

 

So, I was searching for some projects that used this code on Github

 

var app = 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();
});

대충 이런 식으로 쓴 것을 확인했다. server 실행할 때 필요한 파일에 넣는다는 것을 알았다. (나의 경우엔 app.js) 

I checked some projects that use code like that. They used that code on the file that needs for the server-side started to run (In my case, it was app.js).

결말

결말

수정하고 server 쪽을 다시 npm start 하니까 됐다 :)

After I update it and re-start the server, it works well :)

728x90