我们的服务器已经可以从客户端接收字符串。

我们希望客户返回响应并将其显示在文本区域中。

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");


为了进行测试,我们使用本地主机的URL。以后它将是跨域的。
这是网站

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>


我们想扩展这里的代码。

最佳答案

您需要发送响应(res)。

if(req.method=='POST') {
    var body='';
    req.on('data', function (data) {
        body +=data;
    });
    req.on('end',function(){
        res.send(200, "The request's body: " + body);
        var POST =  qs.parse(body);
        console.log(POST);
    });

关于javascript - GET/POST node.js(跨域),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15398530/

10-12 12:50
查看更多