javascript - XMLhttpRequest with a node js server with express -
for reason don't know can't use xmlhttprequest in local server created in node js , express. let me show you... here server in node js:
var express = require('express'), app = express.createserver(); app.get('/count', function(req, res) { res.type('text/plain'); res.write('hello!') res.end(); }); app.listen(4003);
and runs jus fine! when acess localhost:4003/count see "hello!".
now server o.k, let's check html page:
<script> var xmlhttp = new xmlhttprequest(); var resp = "" xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate==4 && xmlhttp.status==200){ resp = xmlhttp.responsetext; } } var cam = "localhost:4003/count" function show(){ xmlhttp.open("get",cam, true); xmlhttp.send(); alert(resp); } </script> <center><h1><div style="color:#339966"> <input type="button" value="return of /count" onclick="javascript:show()"> </div> </h1>
so, don't work =[, i've tried to:
- change
localhost:4003/count
value of variablecam
,http://localhost:4003/count
,127.0.0.1:4003/count
. - open in firefox, safari , chrome.
- when try see
xmlhttp.status
alert()
shows '0
'. (but page open in browser)
along timing issues morgan covered...
when including host in url, needs prefixed
//
.var cam = "//localhost:4003/count";
otherwise, it'll treated relative path
localhost:4003
directory name.you have deal same-origin policy when using ajax.
so, if you're trying use
file://
page, won't typically work well.file
protocol doesn't have origin, can't pass sop, resulting in errors similar to:origin null not allowed access-control-allow-origin.
the easiest solution serve page application.
you can either
static()
middleware.// `get /` serve `./public/index.html` app.use(express.static(__dirname + '/public'));
or route sends file itself.
app.get('/', function (req, res) { res.sendfile(__dirname + '/public/index.html'); });
then, access page from:
http://localhost:4003/
also, both page ,
count
served same origin, url can relative-from-root:var cam = "/count";
Comments
Post a Comment