nodejs get api
nodejsTo 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.
Other Article on Tag nodejs
- - axios Request path contains unescaped characters
- - CryptoJS.HmacSHA256 Cannot read properties of undefined (reading 'sigBytes')
- - encrypt by java and decrypt by node
- - fetch function mode sors, no-cors, same-origin
- - How to set value for NODE_TLS_REJECT_UNAUTHORIZED
- - it error Request path contains unescaped characters
- - java vs nodejs
- - nodejs add redis
- - nodejs call api get request
- - nodejs connect mysql database