I'm new to nodejs and currently using localhost to run mock APIs.
index.js -
const express = require("express");
const api = require("./routes/api");
const app = express();
// Routes
app.use("/api", api); // route api
routes/api/index.js -
const router = express.Router();
router.get("/path-to-certain-resource", async (req, res) => {
});
//...
router.post("/path-to-another-resource", async(req,res) => {
});
I need to create a new API using a predefined url -
e.g. https://example.com/api/v1/users
How can I do this?
Related
I am new to Node.js and trying to make an API which would add a user into MongoDB database, my problem is I am Unable to access any properties of res & req in my controller. I tried searching for answer on SO but it seems the problem lies how you export the routes but the more I see the answers the more I get confused.
Here is part of my Server.js file,
const express = require("express");
const { readdirSync } = require("fs");
const dotenv = require("dotenv");
const app = express();
const mongoose = require("mongoose");
app.use(cors(options));
app.use(express.json());
This is how I am registering Routes,
readdirSync("./routes").map((r) => app.use("/", require("./routes/" + r))); //here route folder is being registered as a controller
Now in my Routes/User.js
const express = require("express");
const { register } = require("../controllers/user");
const router = express.Router();
router.get("/register", register);
module.exports = router;
In Controller/User.js
exports.register = async (req, res) => {
// here is the problem, when this controller is hit, i want to send response back
// like res.send("user added successfully") but I am unable to access req."send" or "body"
};
I have Tried using app.use(express.json()); answer on some forums but to no avail.
Given a simple Express app
const express = require('express')
const app = express()
app.get('/users/:userId', (req, res) => {
console.log(req.orginalUrl) // /users/1
console.log(req.route.path) // /users/:userId
res.json({})
})
It gives me the right and complete route schema req.route.path.
But if we use a router to abstract the first part of the URI then it doesn't give the full route schema anymore.
const express = require('express')
const app = express()
const users = express.Router()
.get(':userId', (req, res) => {
console.log(req.orginalUrl) // /users/1
console.log(req.route.path) // /:userId
res.json({})
})
app.use('/users', users)
It there a way to get /users/:userId while using routers?
You just have to concatenate baseUrl and path like this :
let fullPath = req.baseUrl + req.route.path;
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"));
tldr
Ok i've been trying to get a file upload server working for a few days now and evrything i try just returns cannot get.
i'm currently trying the setup below but it is not working
code
here is server.js
const express = require("express");
const upload = require("./upload");
const cors = require("cors");
var router = express.Router();
var app = express();
const server = express();
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
server.use(cors(corsOptions));
router.get("/", function(req, res) {
res.render("index", { title: "Express" });
});
server.post("/upload", upload);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
Below is upload.js
const IncomingForm = require("formidable").IncomingForm;
module.exports = function upload(req, res) { var form = new IncomingForm();
form.on("file", (field, file) => {
// Do something with the file
// e.g. save it to the database
// you can access it using file.path
console.log("thisno werk"); }); form.on("end", () => {
res.json(); }); form.parse(req); };
Let's mean server as the result of the const server = require('express')();, and router as the result of const router = require('express').Router();.
server is an instance of your Express server while router is an instance of API endpoints router. You don't only need to write your router router.get();, but you also need to set the appropriate files (so-called controllers) for handling API requests.
So your code should have this line: server.use('/', yourController); or simply server.get('/', handlingFunction); if you don't have API sections.
However, if you use routers, then you need the first variant.
Your POST /upload method works great because it's configured on the app level. But you need to fix your GET / method because it's configured on the router level that is unused in your app.
Source: Express routing
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')))