我在使用Node JS在浏览器中显示HTML响应数据时遇到问题

时间:2015-03-23 21:52:57

标签: node.js serverside-javascript

所以我要求学校网页应用程序显示课程列表的信息。一切正常,因为我可以将HTML响应输出到控制台或将HTML响应写入HTML文件。但我想做的是直接在浏览器上显示响应。提前感谢你的帮助。我的代码如下:

var querystring = require('querystring');
var http = require('http');

var postData = querystring.stringify({
    "semester": "20161Summer 2015",
    "courseid": "",
    "subject": "IT  INFORMATION TECHNOLOGY",
    "college": "",
    "campus": "1,2,3,4,5,6,7,9,A,B,C,I,L,M,N,P,Q,R,S,T,W,U,V,X,Y,Z",
    "courselevel": "",
    "coursenum": "",
    "startTime": "0600",
    "endTime": "2359",
    "days": "ALL",
    "All": "All Sections"
});

var options = {
    hostname: 'www3.mnsu.edu',
    port: 80,
    path: '/courses/selectform.asp',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postData.length
    }
};

http.createServer(function(request, response){  

var req = http.request(options, function(res){
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');

    res.on('data', function(chunk){
        console.log('BODY: ' + chunk);//Here I can display the response on the console.
        res.write(chunk);//Here I want to display the response on the browser but I get an error.
    });

    res.on('end', function(){
        console.log('END OF TRANSFER');
    });
});

req.on('error', function(e){
    console.log('problem with request: ' + e.message);
});

// write data to request body
req.write(postData);
req.end();
}).listen(8000);

1 个答案:

答案 0 :(得分:1)

on('data')事件回调中,您使用错误的响应对象进行编写。

您应该设置浏览器响应的内容类型,写入来自外部页面的数据块,并在数据完成时关闭浏览器响应。像这样:

http.createServer(function(browserRequest, browserResponse) {
    //Set the content type header of the response sent to the browser
    browserResponse.writeHead(200, {
        'Content-Type': 'text/html'
    });

    // Creating the request executed by the server
    var serverRequest = http.request(options, function(serverResponse) {
        serverResponse.setEncoding('utf8');
        serverResponse.on('data', function(chunk) {
            // Sending data to the browser
            browserResponse.write(chunk);
        });

        serverResponse.on('end', function() {
            // Closing browser response
            browserResponse.end();
        });
    });

    serverRequest.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });

    serverRequest.write(postData);
    serverRequest.end();
}).listen(8000);