To return a text response from an HTTP server written in Typescript using Node.js and Express.js, you can make use of the response
object provided by Express.js.
index.ts219 chars13 lines
In the code above, we create an Express.js app
and add a route handler for a GET
request to the root URL. In the app.get()
function, we pass a callback function that takes req
(request) and res
(response) objects as arguments. We then call res.end()
to send a response back to the client with the string "Hello World!".
Once the server is started with app.listen()
, it will listen for incoming requests on port 3000.
Using Promises, you can also return a text response asynchronously as follows:
index.ts318 chars15 lines
In this example, we use the fetch()
function to make an HTTP request to an API and get some data, which we then return as a text response using res.end()
. The async
keyword is used in the callback function to allow us to use await
for the asynchronous fetch()
and text()
functions.
gistlibby LogSnag