Node.js - JavaScript - HTML - XMLHttpRequest cannot load - Stack Overflow

Node.js - Javascript - HTML - XMLHttpRequest cannot loadBasically i have 2 scripts posted below one nod

Node.js - Javascript - HTML - XMLHttpRequest cannot load

Basically i have 2 scripts posted below one node.js and 1 javascript/html

i am posting data to my node.js file but i recieve this error and cannot see the result of the nodes.js on my html page.

XMLHttpRequest cannot load http://192.168.2.109:8111/?name=nknk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.109:8111' is therefore not allowed access

Here is my Node.js file:

    var url = require('url');
    var http = require('http');
    var server = http.createServer(function (request, response) {
    var queryData = url.parse(request.url, true).query;
    response.writeHead(200, {"Content-Type": "text/plain"});

    if (queryData.name) {
    var basevalue = queryData.name;
    var value = basevalue.split (":");
    var exec = require('child_process').exec;

    console.log(value[0]);
    console.log(value[1]);

    exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {

    response.end(stdout);

    });

    } else {
    response.end("Contact Admin - Not Working\n");
    }
    });


    server.listen(1234);

here is my html/javascript:

<script src="//ajax.googleapis/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Wele To ....</title>
<script type="text/javascript">
function textareaToArray(t){
    return t.value.split(/[\n\r]+/);
}
function showArray(msg){
    for(i = 0; i < msg.length; i++) {
        // something per item
        var data = {}; //your own data
     $.post("http://192.168.2.109:8111" + "?" + $.param({name: msg[i]}), data);

    }
    // the old code
    document.getElementById("message").innerHTML = msg.join("&#013;");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>

Can someone help me fix this so that i can get the result back to my html without this error

----edit 

this is code i am trying i can still not see the response data from the node.js server i need to see the response from the exec mand that my node server runs i know this takes about 40 seconds to plete but i still do not see anything outputted to html

node.js

var url = require('url')
var http = require('http')
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});

if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
var basevalue = queryData.name;
var value = basevalue.split (":");

console.log(value[0]);
console.log(value[1]);

var exec = require('child_process').exec;

exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {

response.end('_stdout(\'{"content": "blablabla"}\')');

});

} else {
response.end("Contact Admin - Not Working\n");
}
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8999);
~

javascript html

    <script src="//ajax.googleapis/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Wele To ....</title>
<script type="text/javascript">
function textareaToArray(t){
    return t.value.split(/[\n\r]+/);
}
function showArray(msg){
    for(i = 0; i < msg.length; i++) {
        // something per item
     //   var data = {}; //your own data
    //$.post("http://192.168.2.109:8121" + "?" + $.param({name: msg[i]}), data);
    $.ajax({
    url: 'http://192.168.2.109:8999' + '?' + $.param({name: msg[i]}),
    dataType: "jsonp",
    jsonpCallback: "_stdout",
    cache: false,
    timeout: 5000,
    success: function(data) {
    function doSomethingWithData(data) { $('#message').val(data.content); }

    },
    error: function(jqXHR, textStatus, errorThrown) {
    handleError(data);
    }
    });     

    }
    // the old code
    document.getElementById("message").innerHTML = msg.join("&#013;");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>

Node.js - Javascript - HTML - XMLHttpRequest cannot load

Basically i have 2 scripts posted below one node.js and 1 javascript/html

i am posting data to my node.js file but i recieve this error and cannot see the result of the nodes.js on my html page.

XMLHttpRequest cannot load http://192.168.2.109:8111/?name=nknk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.109:8111' is therefore not allowed access

Here is my Node.js file:

    var url = require('url');
    var http = require('http');
    var server = http.createServer(function (request, response) {
    var queryData = url.parse(request.url, true).query;
    response.writeHead(200, {"Content-Type": "text/plain"});

    if (queryData.name) {
    var basevalue = queryData.name;
    var value = basevalue.split (":");
    var exec = require('child_process').exec;

    console.log(value[0]);
    console.log(value[1]);

    exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {

    response.end(stdout);

    });

    } else {
    response.end("Contact Admin - Not Working\n");
    }
    });


    server.listen(1234);

here is my html/javascript:

<script src="//ajax.googleapis./ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Wele To ....</title>
<script type="text/javascript">
function textareaToArray(t){
    return t.value.split(/[\n\r]+/);
}
function showArray(msg){
    for(i = 0; i < msg.length; i++) {
        // something per item
        var data = {}; //your own data
     $.post("http://192.168.2.109:8111" + "?" + $.param({name: msg[i]}), data);

    }
    // the old code
    document.getElementById("message").innerHTML = msg.join("&#013;");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>

Can someone help me fix this so that i can get the result back to my html without this error

----edit 

this is code i am trying i can still not see the response data from the node.js server i need to see the response from the exec mand that my node server runs i know this takes about 40 seconds to plete but i still do not see anything outputted to html

node.js

var url = require('url')
var http = require('http')
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});

if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
var basevalue = queryData.name;
var value = basevalue.split (":");

console.log(value[0]);
console.log(value[1]);

var exec = require('child_process').exec;

exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {

response.end('_stdout(\'{"content": "blablabla"}\')');

});

} else {
response.end("Contact Admin - Not Working\n");
}
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8999);
~

javascript html

    <script src="//ajax.googleapis./ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Wele To ....</title>
<script type="text/javascript">
function textareaToArray(t){
    return t.value.split(/[\n\r]+/);
}
function showArray(msg){
    for(i = 0; i < msg.length; i++) {
        // something per item
     //   var data = {}; //your own data
    //$.post("http://192.168.2.109:8121" + "?" + $.param({name: msg[i]}), data);
    $.ajax({
    url: 'http://192.168.2.109:8999' + '?' + $.param({name: msg[i]}),
    dataType: "jsonp",
    jsonpCallback: "_stdout",
    cache: false,
    timeout: 5000,
    success: function(data) {
    function doSomethingWithData(data) { $('#message').val(data.content); }

    },
    error: function(jqXHR, textStatus, errorThrown) {
    handleError(data);
    }
    });     

    }
    // the old code
    document.getElementById("message").innerHTML = msg.join("&#013;");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>
Share Improve this question edited Feb 17, 2014 at 22:15 user3316689 asked Feb 17, 2014 at 20:59 user3316689user3316689 511 silver badge6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Apparently, your web application is not hosted on the same host as your nodejs server, thus, you are violating the same origin policy.

You can use JSONP:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_stdout(\'{"content": "blablabla"}\')');
}).listen(1234);

And your call:

$.ajax({
    url: 'http://192.168.2.109:8111' + '?' + $.param({name: msg[i]}),
    dataType: "jsonp",
    jsonpCallback: "_stdout",
    cache: false,
    timeout: 5000,
    success: function(data) {
        doSomethingWithData(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        handleError(data);
    }
});

This is Same Origin Policy (http://en.wikipedia/wiki/Same-origin_policy). Modify your response at the following way:

response.writeHead(200, {
    "Content-Type": "text/plain",
    "Access-Control-Allow-Origin":"*"
});

My solution is simple.Just require cors module inside the server script side. Due to CORS(Cross Origin Resource Sharing),which is disabled unless enabled otherwise in most of the modern browser. In node require cors module in the application and use it accordingly.

Ex:

var cors=require(‘cors’);
var app=express();
app.use(cors());

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745562539a4633192.html

相关推荐

  • Node.js - JavaScript - HTML - XMLHttpRequest cannot load - Stack Overflow

    Node.js - Javascript - HTML - XMLHttpRequest cannot loadBasically i have 2 scripts posted below one nod

    16小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信