How to write a Node.js API? Create a server and define HTTP routes to handle requests from clients. Handle requests and retrieve or write data from the database as needed. Use res.json() to send data as a JSON response. Use res.status() and res.send() to handle errors and send response codes. Use server callbacks and asynchronous functions to handle HTTP requests.
How to write an API in Node.js
Writing a Node.js API involves creating a server and defining HTTP routes to handle requests from clients. Here are the steps on how to write an API using Node.js:
1. Create a Node.js server
Use the http
module of Node.js Create a server:
<code class="javascript">const http = require('http'); const server = http.createServer((req, res) => { // 处理请求... }); server.listen(3000, () => { console.log('Server listening on port 3000'); });</code>
2. Define HTTP routing
Use server.get()
, server.post()
Define HTTP routes and other methods to handle different HTTP request types:
<code class="javascript">server.get('/api/users', (req, res) => { // 处理 GET 请求并获取用户... }); server.post('/api/users', (req, res) => { // 处理 POST 请求并创建用户... });</code>
3. Processing requests
In the route callback, process the request and retrieve it from the database as needed Retrieve or write data. For example:
<code class="javascript">server.get('/api/users', async (req, res) => { const users = await User.find(); res.json(users); });</code>
4. Send response
Use the res.json()
method to send the data back to the client as a JSON response:
<code class="javascript">res.json({ success: true, data: users });</code>
5. Handling errors
Use the res.status()
and res.send()
methods to handle errors and send them to The client sends the appropriate response code:
<code class="javascript">server.get('/api/users/:id', async (req, res) => { try { const user = await User.findById(req.params.id); if (!user) { res.status(404).send('User not found'); return; } res.json(user); } catch (err) { res.status(500).send('Internal server error'); } });</code>
The above is the detailed content of How to write an interface with nodejs. For more information, please follow other related articles on the PHP Chinese website!