Home > OS >  Do guidelines exist for the second parameter of `response.writeHead` when submitting the errored res
Do guidelines exist for the second parameter of `response.writeHead` when submitting the errored res

Time:04-25

I tried to send the below message

Invalid query parameters detected:


=== Error No. 1 ==========
Required property is missing

● Property / element: 'Deserialized query parameters of http://127.0.0.1:90/api/categories route.paginationPageNumber'
This property is 'undefined' while has been marked as required.

● Property / element specification:
{
  "type": "number",
  "required": true,
  "numbersSet": "NATURAL_NUMBER"
}
● Actual value: undefined
● Value before first pre-validation modification: undefined

< etc. >

via

response. // (is "http.ServerResponse")
   writeHead(HTTP_StatusCodes.badRequest, errorMessage).
   end();

in errorMessage variable . Below NodeJS error occured:

Caught error:
TypeError [ERR_INVALID_CHAR]: Invalid character in statusMessage
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.writeHead (node:_http_server:322:11)
    // ...

I have no idea on which character NodeJS complains about (possibly slashes), but I suppose what I am using the second parameter of writeHead improperly. If so, there are two questions:

  • Which errorMessage must be like? Just "Bad request" or "Unauthorized"?
  • Where I should append above login message instead?

CodePudding user response:

You can refer to this for official documentation

You can send a response like this

let body = error_message; // or whatever response you want to send back to the sender

response
  .writeHead(STATUS_CODE, {
    'Content-Type': 'your_header_content_type'
  }).end(body);

As for the status codes, you can refer the mozilla convention here (which is quite widely used)

  • Related