Frontend send ajax request to Egg has an error of CORS or OPTIONS 405 Method Not Allowed
See original GitHub issueGoal: Egg works as simple RESTful api server, Frontend communicates with Egg via Ajax requests. Browser (Chrome latest) has Cross Origin enabled by default. Egg enabled CORS, frontend sends a request and need to get the payload back from Egg.
I have created an Angular frrontend and trying to talk to Egg ONLY via RESTful api. But I run into an issue of CORS. This is the error message from browser console:
XMLHttpRequest cannot load http://localhost:7001/api/user. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
I am not sure that it is an error from front end, or egg, or its plugins: egg-rest, egg-cors, or just an User error.
Here is how you can duplicate the issue.
1st Use [examples/restful_api] , then enabled cors
plugins at [here](https://github.com/eggjs/egg/tree/master/examples/restful_api)(https://github.com/eggjs/egg/blob/master/examples/restful_api/config/plugin.js#L3)
// restful_api/config/plugin.js
exports.cors = true;
exports.rest = true;
Note: it works on curl
with/without cors=true
. and all CRUD operation works as expected.
2nd Frontend ajax request: Here I included a simple HTML with jquery ajax caller.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<script>
jQuery.ajax({
url: "http://localhost:7001/api/user",
type: "GET",
contentType: "application/json",
async: true,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Test-Header', 'test-value');
},
success: function( users ) {
console.log('users: ', users)
}
});
</script>
</body>
</html>
3rd - Load up in the browser, I see the error below:
Error on terminal console
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (6 by maintainers)
Top GitHub Comments
Although I know egg server can serve a static webpage, i want to scale my client side and node.js server side separately in two docker containers managed by kubernetes. so that they are not bundled inside a same container as a single process. Kubernetes can handle scale them separately based on the resources.
Why your angular app and rest api are starting at different server, the best practice is Do everything in egg server.
We should add some view example. Matt Ma notifications@github.com于2016年8月15日 周一上午11:52写道: