我们的服务器已经可以从客户端接收字符串。GET/POST node.js(跨域)
我们希望客户得到回复并将其显示在textarea中。
app.js:
var sys = require ('util'),
url = require('url'),
http = require('http'),
qs = require('querystring');
var stringforfirefox = 'hi man!';
http.createServer(function (req, res) {
if(req.method=='POST') {
var body='';
req.on('data', function (data) {
body +=data;
});
req.on('end',function(){
var POST = qs.parse(body);
console.log(POST);
});
}
else if(req.method=='GET') {
var url_parts = url.parse(req.url,true);
console.log(url_parts.query);
}
}).listen(1337, "127.0.0.1");
为了进行测试,我们使用本地主机地址。之后它将是跨域的。 这里是网站
的index.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<script>
document.onkeypress = function keypressed(e){
if (e.keyCode == 112) {
httpGet('http://localhost:1337/index77?title=message_for_server') ;
}
if (e.keyCode == 113) {
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("textarea1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","http://localhost:1337/index77",true);
xmlhttp.send("fname=Henry&lname=Ford");
}
}
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false);
xmlHttp.send("fname=Henry&lname=Ford");
alert(xmlHttp.responseText);
}
</script>
</head>
<body>
<form>
<p>
<textarea id="textarea1" cols="25" rows="25" name="textfeld"></textarea>
</p>
</form>
</body>
</html>
我们想延长这种代码,我们在这里。
发生以下错误:_TypeError:Object# has no met hod'send'_ –
2013-03-14 00:08:40
@MichaelMoeller'res.statusCode = 200; res.end(“request's body:”+ body);'(ref:['res.write()'](http://nodejs.org/api/http.html#http_response_write_chunk_encoding),['res.end ()'](http://nodejs.org/api/http.html#http_response_end_data_encoding))'res.send()'可从其他库中获得,例如[快递](http://expressjs.com/api.html#res.send)。在该说明中,您可以从[Connect](http://www.senchalabs.org/connect/)中找到['bodyParser()'](http://expressjs.com/api.html#bodyParser)有用。 – 2013-03-14 00:20:18
@JonathanLonowski感谢您的支持。我们使用这个代码,但客户端没有显示任何反应。 – 2013-03-14 00:42:57