return a text response from a http server in typescript

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.ts
import * as express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.end('Hello World!');
});

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});
219 chars
13 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.ts
import * as express from 'express';

const app = express();
const port = 3000;

app.get('/', async (req, res) => {
  const result = await fetch('https://api.example.com/some-data');
  const data = await result.text();
  res.end(data);
});

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});
318 chars
15 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