2

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.

2
  • 1
    You might need some additional headers, see this post: stackoverflow.com/questions/7067966/… IIRC you need at least the allowed methods one. Commented May 6, 2014 at 5:16
  • also i fix my problem with this answer. the problem is come from post . Commented May 6, 2014 at 7:56

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.