api endpoints in express for next js code example
Example 1: reactjs loop through api response in react
import React from 'react';
class Users extends React.Component {
constructor() {
super();
this.state = { users: [] };
}
componentDidMount() {
fetch('/api/users')
.then(response => response.json())
.then(json => this.setState({ users: json.data }));
}
render() {
return (
<div>
<h1>Users</h1>
{
this.state.users.length == 0
? 'Loading users...'
: this.state.users.map(user => (
<figure key={user.id}>
<img src={user.avatar} />
<figcaption>
{user.name}
</figcaption>
</figure>
))
}
</div>
);
}
}
ReactDOM.render(<Users />, document.getElementById('root'));
Example 2: fetch api based on id nodejs and mongodb
// contactModel.jsvar mongoose = require('mongoose');// Setup schemavar contactSchema = mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true }, gender: String, phone: String, create_date: { type: Date, default: Date.now }});// Export Contact modelvar Contact = module.exports = mongoose.model('contact', contactSchema);module.exports.get = function (callback, limit) { Contact.find(callback).limit(limit);}
Example 3: fetch api based on id nodejs and mongodb
// Import expresslet express = require('express');// Import Body parserlet bodyParser = require('body-parser');// Import Mongooselet mongoose = require('mongoose');// Initialise the applet app = express();// Import routeslet apiRoutes = require("./api-routes");// Configure bodyparser to handle post requestsapp.use(bodyParser.urlencoded({ extended: true}));app.use(bodyParser.json());// Connect to Mongoose and set connection variablemongoose.connect('mongodb://localhost/resthub', { useNewUrlParser: true});var db = mongoose.connection;// Added check for DB connectionif(!db) console.log("Error connecting db")else console.log("Db connected successfully")// Setup server portvar port = process.env.PORT || 8080;// Send message for default URLapp.get('/', (req, res) => res.send('Hello World with Express'));// Use Api routes in the Appapp.use('/api', apiRoutes);// Launch app to listen to specified portapp.listen(port, function () { console.log("Running RestHub on port " + port);});