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;
Related
Here are my server-side index.js:
import Express from 'express';
import fileUpload from 'express-fileupload';
import http from 'http';
import TestRouter from "./TestRouter.js";
let app = new Express();
let httpServer = http.createServer(app);
app.use(Express.json());
app.use(fileUpload({debug:true}));
app.post('/test/uploadFile',async (req, res, next) => {
console.log(req.body);
Object.keys(req.files).forEach(key=>{
console.log("Name:"+req.files[key].name);
console.log("MIMETYPE:"+req.files[key].mimetype);
console.log("File size:"+req.files[key].size);
console.log("==================================");
});
res.status(200).end();
});
let portNo=8080;
httpServer.listen(portNo, () => {
console.log('Express server is running on localhost:'+portNo);
})
It works fine.
When I change the code to :
import Express from 'express';
import fileUpload from 'express-fileupload';
import http from 'http';
import TestRouter from "./TestRouter.js";
let app = new Express();
let httpServer = http.createServer(app);
app.use(Express.json());
app.use(fileUpload({debug:true}));
app.use('/test', TestRouter);
let portNo=8080;
httpServer.listen(portNo, () => {
console.log('Express server is running on localhost:'+portNo);
})
And the TestRouter.js source code is below:
import Express from 'express';
let wrapper = function () {
const router = Express.Router();
router.post('/:action', async (req, res, next) => {
console.log(req.params.action);
switch (req.params.action) {
case "uploadFile":
console.log("hi");
res.status(200).end();
break
default:
next();
break
}
});
return router;
}
export default wrapper;
I find that the TestRouter does not be triggered.
Why?
Finally, I get it working by replacing the following statement:
app.use('/test', TestRouter);
with
app.use('/test', TestRouter());
I have three files when I try running index.js file DB work well but router does not work and if run server.js DB and router does not work
server
import express from 'express'
import cors from 'cors'
import restaurants from './api/restaurants.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/restaurants", restaurants)
app.use("*", (req, res) => res.status(404).json({error: "Not Found"})) // any router not found in our routers
export default app;
index
import app from './server.js'
import mongodb from 'mongodb'
import dotenv from 'dotenv'
dotenv.config()
const mongoClient = mongodb.MongoClient
const port = process.env.PORT || 8000
mongoClient.connect(
process.env.RESTREVIEWS_DB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
).catch((e) => {
console.log(e.stack)
process.exit(1)
}).then(async client => {
app.listen(port, () => {
console.log(`app listen in link http://localhost:${port}/api/v1/restaurants`)
})
})
router
import express from 'express'
const router = express.Router();
router.get('/api/v1/restaurants', (req, res) => {
res.status(200).send("HelloWorld");
})
export default router
I'm trying to implement a dynamic import inside a express.js router
now I have a bellow code
HelloWorldController.js
export const helloWorld = function (req, res) {
res.send('hello world')
}
router.js
export default async function (app) {
app.use('/', await ( async function () {
const helloWorldController = await import('./helloWorldController.js')
const router: express.Router = express.Router()
router
.get('/', helloWorldController.helloWorld)
return router
})
}
server.js
import express from 'express'
import router from './router.js'
const app = express()
router(app)
app.listen(3000, function(){
logger.ready(`Web Server is running on port 3000`)
})
This is the result I'm getting when I run server.js
I have a 404 error
GET / 404 18.761 ms - 25
This is working fine
router.js
import * as helloWorldController './helloWorldController.js'
export default async function (app) {
app.use('/', await ( async function () {
const router: express.Router = express.Router()
router
.get('/', helloWorldController.helloWorld)
return router
})
}
** What am I doing wrong? **
ES6 import syntax is not supported yet in node js,
try this syntax const {express} = require("express")
I am trying to build a basic Express api and am running in to an odd module not found error. Before introducing TypeScript to my project, I never got this error. This has been quite frustrating to resolve. I appreciate any suggestions on why I am getting this error and how to resolve.
server.ts
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
//import * as api from "api"; also tried this
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/api', require('./api'));
app.use('*', (req, res, next) => {
let error = new Error('404: not found');
next(error);
});
app.use((error, req, res, next) => {
res.status(500).send({
error: {
message: error.message
}
});
});
const port = 3000;
app.listen(port, () => {
console.log('listening on port', port);
});
module.exports = app;
api/api.ts
import express from "express";
const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
module.exports = router;
With typescript, we don't use module.exports but export directly like so:
import express from "express";
export const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
Then we can get the router with
import {router} from './api'
New to nodejs world. Trying to create a REST Service with express and I'm stuck trying to debug this issue... I want to call a GET resource that has a route param in router.use('/applications/:appId/messages', messageRoutes);
index.js
import Promise from 'bluebird';
import mongoose from 'mongoose';
import config from './config/env';
import app from './config/express';
// plugin bluebird promise in mongoose
mongoose.Promise = Promise;
// connect to mongo db
mongoose.connect(config.db, { server: { socketOptions: { keepAlive: 1 } } });
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${config.db}`);
});
const debug = require('debug')('express-mongoose-es6-rest-api:index');
// listen on port config.port
app.listen(config.port, () => {
debug(`server started on port ${config.port} (${config.env})`);
});
export default app;
/config/express.js
import express from 'express';
import bodyParser from 'body-parser';
import routes from '../server/routes';
const app = express();
// parse body params and attache them to req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
[...]
// mount all routes on /api path
app.use('/api', routes);
[...]
export default app;
/server/routes/index.js
import express from 'express';
import userRoutes from './user';
import messageRoutes from './message';
import applicationRoutes from './application';
import authRoutes from './auth';
const router = express.Router(); // eslint-disable-line new-cap
// mount message routes at /messages
router.use('/applications/:appId/messages', messageRoutes);
export default router;
/server/routes/message.js
import express from 'express';
import validate from 'express-validation';
import paramValidation from '../../config/param-validation';
import messageCtrl from '../controllers/message';
const router = express.Router(); // eslint-disable-line new-cap
router.route('/')
/** GET /api/applications/:appId/messages - Get list of messages */
.get(messageCtrl.getByAppId);
export default router;
/server/controllers/message.js
import mg from 'mongoose'
import Message from '../models/message';
import moment from 'moment';
function getByAppId(req, res, next) {
//return res.json(req.message);
console.log(req);
}
export default {getByAppId};
The result of console.log(req) is a printout of the request object but the params array is blank.
baseUrl: '/api/applications/57fcf8129eb1d52f1cb10332/messages',
originalUrl: '/api/applications/57fcf8129eb1d52f1cb10332/messages/',
_parsedUrl:
Url {
protocol: null,
slashes: null,
[...]
params: {},
query: {},
Can anyone offer any guidance? Much appreciated. Not sure why the params are blank. Could it be the :appId variable declaration in express router.use() statement?