How to get JSON Array from external json file without using jQuery? - javascript

I am working on creating the classical car API. Now I'm trying to pull a JSON Array from an external file.
I made a step toward a resolution, however my "solution" will return the full object, instead of the array json.
This is from the vehicles.js file, found under api/routes/
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const router = express.Router();
router.get('/', (req, res, next) => {
res.status(200).sendFile(path.join(__dirname, '../resources', 'vehicles.json'));
});
export default router;
The app.js looks like this:
import express from 'express';
const app = express();
import vehiclesRoute from './api/routes/vehicles.js';
app.use('/vehicles', vehiclesRoute);
export default app;
Something else I tried was in the lines of:
import parsedJSON from './resources/vehicles.json';
var vehiclesJSON = parsedJSON.vehicles;
router.get('/', (req, res, next) => {
let vehiclesJSONpath = path.join(__dirname, '../resources', 'vehicles.json');
res.status(200).fetch(vehiclesJSONpath)
.then(res => res.json())
.then(data => console.log(data));
});
Is there a way I can do the parsing and include it in the response body of the callback?
Is there maybe a route I need to configure anew, so that the array can be simply extracted?
Thanks!

Will close this. The solution was simple.
'use strict';
let rawdata = fs.readFileSync('api/resources/vehicles.json');
let vehicles = JSON.parse(rawdata);
Then, in order to be able to get it as a response:
router.get('/', (req, res, next) => {
res.status(200).json(vehicles);
});
Saved by: https://stackabuse.com/reading-and-writing-json-files-with-node-js/

Related

node js post 404 not found with router

hello i have a issue i build a project when i start to add the server side
i am using node js express
i create fetch post to spesific url from the database (mongoDB)
and i want to add the users
now
its workd but i try to reconfigure the files and using router and now i get 404 when i try to make the post is upload some code
just need to know where is the bad request
the url i want to fetch is
http://localhost:5000/shopping-cart/user/sign-up
Axios.post("http://localhost:5000/shopping-cart/user/sign-up", user).then((response) => {
console.log(response);
});
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const path = require("path")
const productRouter = require("./routes/product.route");
const userRouter = require("./routes/user.route");
const { setServerConfiguration } = require("./config");
setServerConfiguration(app);
mongoose.connect('mongodb://localhost/shopping-cart-data-base');
app.use("/shopping-cart", productRouter);
app.use("/user/sign-up", userRouter);
app.listen(5000);
const router = require('express').Router();
const errorsHandler = require('../utils/errorsHandler');
const UserModel = require('../models/User');
router.post("/user/sign-up", async (req, res) => {
let body = req.body;
console.log(body)
try{
await UserModel.create({
name: body.name,
username: body.username,
password: body.password,
shoppingHistory: [],
});
res.send(body);
}catch(e){
return errorsHandler(e, req, res);
}
});
module.exports = router;
Your router is mounted on the /user/sign-up prefix:
app.use("/user/sign-up", userRouter);
Which means that all requests that start with /user/sign-up will get passed to your router.
Your router should be routing relative to that prefix, so to make it work, use this:
router.post('/', ...)
Try this url
"http://localhost:5000/user/sign-up"
If you want to use "http://localhost:5000/shopping-cart/user/sign-up" than you need to define route like that, for example:
router.post("shopping-cart/user/sign-up", async (req, res) => {
//Your code
})
404 route not found
app.use("/shopping-cart", productRouter) => route1
app.use("/user/sign-up", userRouter); => route2
route1 other route2
url http://localhost:5000/shopping-cart request route1
url http://localhost:5000/user/sign-up request route2

My backend route is not behaving as it should and not posting anything to MongoDB

I am trying to create a simple CRUD app. I was trying to set up the first backend route but I am stuck and can't figure out what is wrong with my code or what I am missing.
If I try to test the route with Insomnia, it doesn't return any error, but it targets the basic "/" route and returns the console.log('OK') instead of creating an item in MongoDB. Here is my code:
// app.js file
require("./db");
const express = require("express");
const app = express();
require("./config")(app);
const backoffice = require('./routes/backoffice');
app.use('/api/backoffice', backoffice);
app.use('/', (req, res) => {
res.send('OK')
});
module.exports = app;
// route file backoffice.js
const router = require("express").Router();
const Item = require("../models/Item");
router.post('/backoffice', (req, res, next) => {
console.log(req.body);
const {title, description} = req.body;
Item.create({
title,
description
})
.then(response => {
console.log(response)
res.status(200).json({message: 'New item added succesfully'})
})
.catch(err => res.json(err))
})
module.exports = router;

Nodejs Express simple import js file router

how to import the user.json json file into my user.js ? when i type / user the json should be displayed? new version of node I don't understand
index.js
import express from 'express';
import bodyParser from 'body-parser';
import usersRoutes from './routes/users.js';
const app = express();
const PORT = 5000;
app.use(bodyParser.json());
app.use('/users', usersRoutes);
app.get('/', (req, res) => {
res.send('hello');
});
app.listen(PORT, () => console.log(`Server running on port: http://localhost:${PORT}`));
user.js
import express from 'express';
const router = express.Router();
router.get('/', (res, req) => {
res.send();
});
export default router;
import express from 'express';
import userJSON from '../user.json' // < ------- here
const router = express.Router();
router.get('/', (res, req) => {
res.send();
});
export default router;
Depending of the version you are using you either has to use babel or include the --experimental-json-modules flag for the module to work. ** node v.14 does not need anything.
node --experimental-json-modules about.js
import express from 'express';
import userfile from '../user.json' // import the json file
const router = express.Router();
router.get('/', (res, req) => {
res.send(userfile); //this line sends the json
});
export default router;
Instead use the fs module:
const user = require('fs').readFileSync('../user.json', 'utf-8');
You can do it by simply:
import express from 'express';
import user from '../user'; // <---- Don't need even the .json extension.
const router = express.Router();
router.get('/', (res, req) => {
res.send(user);
});
export default router;

Get parameter from previous route handler in express js

Say I have file1.js:
import Router from "express-promise-router";
export const router1 = Router();
router1.get("/", async (req, res) => {
// I want to get here :id from router2 in file2
})
And file2.js (in the same directory for simplicity):
import Router from "express-promise-router";
import { router1 } from "./file1";
export const router2 = Router();
router2.use("/:id/path", router1);
I want to use /:id from file2.js in file1.js (see my comment in example code).
How can I do that?
In other words, how can I percolate '/:something' parameter down the routers chain?
Note - this doesn't work:
router1.get("/", async (req, res) => {
const { params: {id} } = req;
})
I found the answer.
From express api:
So should add the option mergeParams set to true when declaring the router handler.
In general:
const router = express.Router({mergeParams: true});.
For the question's example code in file1.js:
import Router from "express-promise-router";
export const router1 = Router({mergeParams: true});
router1.get("/", async (req, res) => {
const { params: {id} } = req; // now this works
})

Route.get() requires a callback function but got a [object Undefined]. What did I do wrong?

I have checked many answers in other pages and forums, but I still don't get it. What did I do wrong? Help me
*edited. I have added requiring routes and app.use. It looks like function isLOggedIn is not exporting but I don't know how to do that. I did like this in another app, it worked there.
auth-routes.js
const express = require("express"),
router = express.Router(),
passport = require("passport")
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect("/auth/login")
}
module.exports = router
user-routes.js
const express = require("express"),
router = express.Router(),
authRoutes = require("./auth-routes")
router.get("/profile", authRoutes.isLoggedIn, (req, res) => {
res.render("user/profile", {user: req.user})
})
module.exports = router
requring routes
const titleRoutes = require("./routes/title-routes")
const authRoutes = require("./routes/auth-routes")
const userRoutes = require("./routes/user-routes")
app.use
app.use(titleRoutes)
app.use("/auth", authRoutes)
app.use("/user", userRoutes)
In auth-routes.js you don't export isLoggedIn. So in user-routes.js, authRoutes.isLoggedIn is undefined.
You can change:
module.exports = router
into:
exports.isLoggedIn = isLoggedIn
or using module.exports into:
module.exports = { isLoggedIn: isLoggedIn }
A useful link to understand export in nodejs https://www.sitepoint.com/understanding-module-exports-exports-node-js/

Categories