1

I need to send the data from an HTML form using a javascript function to a node.js server running at the same address. For the record, i have a website hosted on my Raspberry PI, using a custom domain. This is the javascript function:

$.post("http://www.website.com:2052/form", formData, function(data){
    ...
    console.log("POST SUCCESS");
    ...
});

This is the code for my node.js server:

app.post('/form', function(req, res){
    ....
    console.log('POST - body: ' + JSON.stringify(req.body));
    res.send({result:"success"});
    ....
});

When i send the form data to the server, i receive it on the server, but i get this on website-side:

Failed to load http://www.website.com:2052/form: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.website.com' is therefore not allowed access.

I understand that i need to add the access control header in the response, but considering they are on the same "ip", why is it needed? Or how can i make the node.js server actually appear on the same domain? Thanks

2
  • Did you try to include the port number on access control header ? Commented Aug 24, 2018 at 18:16
  • app.use(cors()) npmjs.com/package/cors Commented Aug 24, 2018 at 19:24

1 Answer 1

1

You should add this to your node.js server:

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");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  next();
});

You can check out documentation for:

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

1 Comment

Thank i will try it now

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.