Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - Difference between response.send and response.write in node js

I have written a small API which uses the Node js "restify" framework. This API receives a request (actually anything after "/") and then send that request to another server. Get the response back from server and passes the response back to original source of request. For this API I am using both restify server and client.

Below is that API code for better understanding.

var apiServer = require('apiServer');
apiServer.start();

var restify = require('restify');
var assert = require('assert');

function onRequest(request, response, next)
{
    var client = restify.createStringClient({ 
        url: 'http://example.com'
    });

    client.get('/' + request.params[0], function(err, req, res, data) {
        assert.ifError(err);

        response.setHeader('Content-Type', 'text/html');
        response.writeHead(res.statusCode);
        response.write(data);
        response.end();
    });
    next();
}

function start()
{
    var server = restify.createServer();
    server.get(/^/(.*)/, onRequest);
    server.listen(8888);

    console.log("Server has started.");
}

exports.start = start;

Now I need to know the difference between response.write and response.send of Node.js. Because with response.write I can set header and write in it but it is not possible to do anything with headers when I use response.send. When I use response.send with setHeader() or writeHeader() I get this error:

http.js:691
    throw new Error('Can't set headers after they are sent.');
          ^
    Error: Can't set headers after they are sent.

There is also another thing. With response.send() I get the complete HTML output on the screen like:

<!DOCTYPE html>
<html>
<head></head></html> ..... "bla bla bla"

But with response.write I do not get the html on screen but only the text "bla bla bla".

It would be great if someone can explain me the differences.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

response.send(msg) is equal to response.write(msg);response.end();

Which means, send can only be called once, write can be called many times, but you must call end yourself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...