質問

I have two app with nodejs and angularjs.nodejs app has some code like this :

require('http').createServer(function(req, res) {


  req.setEncoding('utf8');
  var body = '';
  var result = '';
  req.on('data', function(data) {
      // console.log("ONDATA");

      //var _data = parseInput( data,req.url.toString());
      var _data = parseInputForClient(data, req.url.toString());



      switch (req.url.toString()) {
          case "/cubes":
              {

and this app host on http://localhost:4000.angularjs app host with node http-server module on localhost://www.localhost:3030.in one of my angularjs service i have some thing like this :

fetch:function(){
         var data = '{somedata:"somedata"}';
        return $http.post('http://localhost:4000/cubes',data).success(function(cubes){
            console.log(cubes);
        });
    }

but when this service send a request to server get this error:

XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access. 

so i search the web and stackoverflow to find some topic and i find this and this . according to these topics i change the header of response in the server to something like this :

res.writeHead(200, {
                          'Content-Type': 'application/json',
                          "Access-Control-Allow-Origin": "*"
                      });
                      res.end(JSON.stringify(result));

but this dose'nt work.I try with firefox,chrome and also check the request with Telerik Fiddler Web Debugger but the server still pending and i get the Access Control Allow Origin error.

役に立ちましたか?

解決

You do POST request, which generates preflight request according to CORS specification: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ and https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Your server should also respond to OPTIONS method (besides POST), and return Access-Control-Allow-Origin there too.

You can see it's the cause, because when your code creates request in Network tab (or in Fiddler proxy debugger) you should see OPTIONS request with ORIGIN header

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top