using node.js/Express/json-server
I am trying to check ( and modify) the request url sent to my API json-server. I wrote as stated the following middleware in my app server.js
// API JSON-SERVER
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
const apiMiddlewares = jsonServer.defaults()
apiServer.use(apiMiddlewares)
...
apiServer.use((req, res, next) => {
console.log('REQUEST: ', req)
next() // Continue to JSON Server Router
})
...
apiRouter = jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json'))
app.use('/api', apiRouter)
but I never get the request displayed
where am I wrong ?
I looked here
https://github.com/typicode/json-server/issues/253
and it seems to me that you never want to instantiate the jsonServer, but only use the router. Since you are using the express server, you should attach the middleware to that.
const express = require('express')
const jsonServer = require('json-server')
const app = express()
app.use((req, res, next) => {
console.log('REQUEST: ', req)
next() // Continue to JSON Server Router
})
app.use('/api', jsonServer.router(path.join(__dirname, '..', 'server', 'db-dev.json')))
Related
I'm building an API for my web app and I was able to successfully send requests to the routes in Post.js when they only had url params. But when I try to create a route like '/allposts' (the last endpoint in Post.js) , I receive a 404 error message on postman. Here's my code:
router.post('/', (req, res) => {
// Endpoint 1 code here
})
router.get('/:id', (req, res) => {
// Endpoint 2 code
})
// This is the route that I can't to send requests to
router.get('/ap', async(req, res) => {
try{
const ap = await P.find()
res.send(ap)
} catch(error){
log(error)
res.status(500).send("error")
}
})
server.js
const express = require('express')
var cors = require('cors')
const fs = require('fs');
const path = require('path');
var app = express()
app.use(express.static(path)
app.use(cors())
const bodyParser = require('body-parser')
app.use(bodyParser.json());
var p = require("./routes/P.js");
app.use('/post', p);
const PORT = process.env.PORT || 3001
app.listen(port, () => {
log(`Listening on port ${PORT}...`)
});
When I send a request to http://localhost:3001/post/ap, I'm getting the a 404 Not Found error, but the first two routes work fine. It seems like routes with url params work, but the allposts route does not. Any help would be greatly appreciated. Thanks.
Main problem is the order of the routes.
router.get('/:id') will be initialized before router.get('/allposts'). So when you want to access /allposts the first router will catch it.
You need to switch the init order.
First router.get('/allposts') then router.get('/:id').
I want to broke down my routers into separate file rather than keeping all API routes in a single file. So i tried to identify user URL using a middle ware and call the api according to the url as you seeing bellow but middleware function is not working . how to solve this?
//HERE IS INDEX.jS file CODE
const express = require("express");
const dotenv = require("dotenv");
const app = express();
const PORT = process.env.PORT || 7000;
app.listen(PORT);
app.use("/users", require("./routes/users/users"));
//==========================================================
//HERE IS users.js FILE CODE
const express = require("express");`enter code here`
const router = require("express").Router();
express().use(selectApi);
function selectApi(req, res, next) {
console.log("this line also not executing")
switch(req.originalUrl){
case '/':
// calling api here from a nother separate file
case '/user/:id'
// calling api here from a nother separate file
}
}
module.exports = router;
There is an example in the Express.js Routing Guide. I've modified it slightly to fit your example.
users.js
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
// calling api here from a nother separate file
})
router.get('/user/:id', function (req, res) {
// calling api here from a nother separate file
})
module.exports = router
index.js
const express = require("express");
const dotenv = require("dotenv");
const app = express();
const PORT = process.env.PORT || 7000;
app.listen(PORT);
app.use("/users", require("./routes/users/users"));
I'm new to express and node js, I recently learned how to write API for express but at the end, I get some sort of problem which not resolved by me after several tries. I could not get a response on localhost:8080/users
src/routes/users.js
const { Router } = require("express");
const router = Router();
const getUsers = (req, res) =>
res.send(Object.values(req.context.models.users));
const getUser = (req, res) =>
res.send(req.context.models.users[req.params.userId]);
router.get("/users/", getUsers);
router.get("/users/:userId", getUser);
module.exports = router;
src/routes/index.js
const user = require("./user");
const message = require("./message");
module.exports = {
user,
message
};
src/index.js
const express = require("express");
const app = express();
// Custom Modules
const routes = require("./routes");
const models = require("./models");
// Application-Level Middleware Starts
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
req.context = {
models,
me: models.users[1]
};
console.log(req.context.models.users);
next();
});
// Used Routes
app.use("/users", routes.user);
app.use("/messages", routes.message);
// App Listning to HTTPS Module
app.listen(process.env.PORT);
You need to fix your endpoints in users.js:
router.get("/", getUsers);
router.get("/:userId", getUser);
The reason is because of app.use("/users", routes.user); in your index.js, where the endpoint for users is set. If you leave /users/ in users.js it would be localhost:8080/users/users/. Same problem might be with /messages.
I'm making express router.
There is some codes like below.
But when I run node this file, it doesn't work.
I think this part make some problem.
This works in Koa but not express.
Could you give me some advice?
const printInfo = (req) => {
req.body = {
method: req.method,
path: req.path,
params: req.params,
};
};
This is the codes in a row.
const express = require('express');
const posts = express.Router();
const printInfo = (req) => {
req.body = {
method: req.method,
path: req.path,
params: req.params,
};
};
posts.get('/', printInfo);
module.exports = posts;
and
const express = require('express');
const api = express.Router();
const posts = require('./posts');
api.use('/posts', posts);
module.exports = api;
and
const express = require('express');
const app = express();
const api = require('./api/index');
app.use('/api', api);
app.listen(4000, () => {
console.log('Example app listening on port 4000!');
});
Your middleware miss the next() call and the router is not configured properly.
Follow this example, is how I always used middleware with Expressjs
middleware.js
// no need to import express/router
module.exports = (req, res, next) => {
// manipulate your body obj
req.body = {
method: req.method,
path: req.path,
params: req.params,
};
// go to the next function
next();
}
routes.js
// only import the router
const router = require('express').Router();
// function for /api/posts
router.route('/posts').post( (req, res) => {
// req.body has been manipulated from the middleware
// do anything you like and call res
res.send("...")
});
// other routes
module.exports = router;
server.js
const express = require('express');
const middleware = require('./middleware');
const routes = require('./routes');
const app = express();
// all calls to /api/* execute the middleware first
app.use('/api', middleware);
// execute the other routes functions
app.use('/api', routes);
app.listen(4000, () => {
console.log('Example app listening on port 4000!');
});
Hy there, I'm trying to learn to make a REST API. I have the following code, where I mention that i have no error. When I try to access localhost:3000 nothing happens it's just reloading a blank page. What am I doing wrong?
Servers.js
const http = require('http');
const app = require('./app').default;
const port = process.env.port || 3000;
const server = http.createServer();
server.listen(port);
App.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works!'
});
});
module.exports = app;
You've not defined any route. Express generator generates the boilerplate code which is use full to start with.
You can also define a route like this:
app.use('/', function (req, res, next) {
return res.render('index', {title: 'DASHBOARD', 'data': ''});
});
Have a look at this doc: https://expressjs.com/en/starter/generator.html