const express = require('express'); const app = express(); app.get('/api/hello', (req, res) => { res.send({ message: 'Hello, world!' }); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`API server listening on port ${port}`); });
npm install express
node server.js
const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); // Secret used to sign the JWT const jwtSecret = 'your-secret-here'; // Middleware function that verifies the JWT function verifyJwt(req, res, next) { // Get the JWT from the request header const token = req.headers['x-access-token']; // If there is no token, return an error if (!token) { return res.status(401).send({ message: 'No token provided' }); } // Otherwise, verify the token jwt.verify(token, jwtSecret, (err, decoded) => { // If the token is invalid, return an error if (err) { return res.status(401).send({ message: 'Invalid token' }); } // If the token is valid, save the decoded token to the request object // and call the next middleware function req.decoded = decoded; next(); }); } app.get('/api/hello', verifyJwt, (req, res) => { res.send({ message: 'Hello, world!' }); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`API server listening on port ${port}`); });
now how to consume:
const apiUrl = 'http://localhost:3000/api/hello'; const jwt = 'your-jwt-here'; fetch(apiUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', 'x-access-token': jwt, }, }) .then((response) => response.json()) .then((data) => { console.log(data); });
now , how to get the token from the server
const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); // Secret used to sign the JWT const jwtSecret = 'your-secret-here'; // User credentials for authentication const users = [ { username: 'user1', password: 'pass1' }, { username: 'user2', password: 'pass2' }, // ... ]; app.post('/api/login', (req, res) => { // Get the user credentials from the request body const { username, password } = req.body; // Find the user in the list of users const user = users.find((u) => u.username === username && u.password === password); // If the user was not found, return an error if (!user) { return res.status(401).send({ message: 'Invalid username or password' }); } // Otherwise, generate a JWT for the user const token = jwt.sign({ user }, jwtSecret); // Return the JWT to the client res.send({ token }); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`API server listening on port ${port}`); });
const apiUrl = 'http://localhost:3000/api/login'; fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'user1', password: 'pass1' }), }) .then((response) => response.json()) .then((data) => { console.log(data); });