nodejs get api

nodejs

To create a Node.js GET API, you can use the built-in http or https modules in Node.js to create a server that listens for incoming requests. Here’s an example:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/api') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    const data = { message: 'Hello, World!' };
    res.end(JSON.stringify(data));
  } else {
    res.writeHead(404);
    res.end();
  }
});

server.listen(3000, () => {
  console.log('Server listening on port 3000');
});

In this example, we’re creating an HTTP server that listens on port 3000. When a request is made to the /api endpoint using the GET method, the server sends back a JSON response with a “message” property. If the request is made to any other endpoint or with any other HTTP method, the server sends a 404 Not Found response.

You can test this API by running the script and visiting http://localhost:3000/api in your web browser or by using a tool like cURL or Postman to send a GET request to the same URL.