Difference between response.setHeader and response.writeHead?

前端 未结 1 1509
北荒
北荒 2020-12-14 06:51

In my application, I have my Nodejs server send a JSON response. I found two ways to do this but I\'m not sure what the differences are.

One way is

v         


        
相关标签:
1条回答
  • 2020-12-14 07:10

    response.setHeader() allows you only to set a singular header.

    response.writeHead() will allow you to set pretty much everything about the response head including status code, content, and multiple headers.

    Consider the NodeJS docs:

    response.setHeader(name, value)

    Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name.

    var body = "hello world";
    response.setHeader("Content-Length", body.length);
    response.setHeader("Content-Type", "text/plain");
    response.setHeader("Set-Cookie", "type=ninja");
    response.status(200);
    

    response.writeHead(statusCode[, statusMessage][, headers]))

    Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

    var body = "hello world";
    response.writeHead(200, {
        "Content-Length": body.length,
        "Content-Type": "text/plain",
        "Set-Cookie": "type=ninja"
    });
    
    0 讨论(0)
提交回复
热议问题