The server doesn't show any response in browser!

I’m on stage, respond with body.
It runs fine when I do
curl -v http://localhost:4221/echo/abc
but when I run same url on browser, it gives me following


why don’t I see anything, and how can I see the actual response I send?

Hi @ArunBohra12, could you upload your code to GitHub and share the link? It will be much easier to debug if I can run it directly.

Here, I did a push to github, a little bit messy but works GitHub - ArunBohra12/http-server

1 Like

The issue was caused by two extra \r\n:

`HTTP/1.1 ${responseStatus}\r\n\r\n${formattedHeaders}\r\n\r\n${responseBody}`

Notice that formatHeaders is appending \r\n as well.


Fix:

`HTTP/1.1 ${responseStatus}\r\n${formattedHeaders}\r\n${responseBody}`

I did change the socket.write to the following, but still get the same issue

    socket.write(
      `HTTP/1.1 ${responseStatus}\r\n${formattedHeaders}\r\n${responseBody}`
    );

maybe it isn’t this problem?
Actually it was the case from the first step, not just from this chapter.

@andy1li I think this is the reason - Net | Node.js v23.7.0 Documentation
The code I wrote, creates a tcp server
But when I try from the browser, it tries to make a http request and doesn’t work

Well, the fix worked on my machine. :sweat_smile:

The code I wrote, creates a tcp server
But when I try from the browser, it tries to make a http request and doesn’t work

Please recall that HTTP operates on top of TCP.


Could you try logging the entire response with console.log before writing it to the socket? What output do you get?


It looks like "Content-Length": 3 is hardcoded and causing issues.

It does work

I get this on the logs

when I go to / path, it doesn’t when I don’t have any content in the body, but when I have the content it renders it

Also, for a reason when I load the page on the browser, or make the curl request it works for the first time but after that it doesn’t work. Maybe you know something about this?

If / doesn’t return any content, “Content-Length” should be set to 0.

In other words, “Content-Length” should be dynamically determined rather than hardcoded to a fixed value.

1 Like

Also, for a reason when I load the page on the browser, or make the curl request it works for the first time but after that it doesn’t work

The server should not close when a connection (socket) closes; otherwise it won’t be able to accept subsequent requests.

works fine now, thank you

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.