I think it's not the hardest problem, but i can't solve it. I have some html, css and javascript code. On a html-page the user can enter a number into a searchfield. The goal is to have this number in my node.js code to do more stuff with it.
My ideas so far:
- create a cookie: worked fine until i had to get this somehow to my node.js code
- browserify: can't work because of security reasons
than i tried the following:
on the server side:
var http = require('http');
http.createServer(function (req, res) {
console.log('Request received');
res.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*' // implementation of CORS
});
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('{"msg": "OK"}');
}).listen(8080, '172.0.0.1');
console.log('Server running at http://172.0.0.1:8080/');
and on the client side i tried first this:
var request = new XMLHttpRequest();
request.open('POST', cookie); // cookie is the text that i would like to transfer
request.setRequestHeader('Content-Type', 'text/*;charset=utf-8');
request.send(cookie);
and then this:
$.ajax({
type: 'POST',
url: 'http://172.0.0.1',
data: '{"data": cookie}', // cookie = my text
crossDomain: true,
success: function (data) {
var ret = jQuery.parseJSON(data);
console.log(ret.msg);
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
console.log('Error connecting to the server.');
}
});
The problem is No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
If i'm calling the server in the browser i get {"msg": "OK"}. That is nice, but how can i get to my cookie text in the node.js code.
I'm new to this node.js, ajax - world. Maybe there is just a little piece missing.