express cant be shown in localhost - express

I am a beginner to express,but in have diffculities when linking with the localhost in my internet.But it works fine a minute ago, it shows no error and with fine console log,but the website just stuck on the url without any error.I am wondering is the bug occur on my script or my internet
my code:
const bodyParser = require('body-parser')
const express = require('express')
const app = express()
console.log("ff")
const mongoose=require('mongoose')
mongoose.set('strictQuery',false)
require('dotenv/config')
const db=mongoose.connection
db.on('error',(error)=>console.error(error))
db.once('open',()=> console.log('connect to db'))
mongoose.connect(
process.env.DB_CONNECTION
,{ useNewUrlParser:true })
app.use(logger)
app.use(bodyParser.json)
app.get('/',logger,(req,res)=>{
console.log("ddd")
//res.status(500)
res.json({ username : "alex"})
})
const userRouter = require('./routes/users')
function logger(req,res,next){
console.log(req.originalUrl)
next()
}
app.use('/users',userRouter)
app.listen(3000)

I think the bodyParser is the problem.
I changed it and now your code works for me
use this:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); //<- () missing

Related

express and moralis token price API not fetching json data in console

I've been following video link from Moralis web3 (youtube) meanwgile I got stuck when I need to fetch data using token price Moralis API. I want the price details to be printed in the console when i do
npm start
the expected output in console is:
{
nativePrice: {
value: '13851123944545175839',
decimals: 18,
name: 'Ether',
symbol: 'ETH'
},
usdPrice: 23176.58785953117,
exchangeAddress: '0x1f98431c8ad98523631ae4a59f267346ea31f984',
exchangeName: 'Uniswap v3'
}
In localhost it should return empty json object '{}' but when I opened the same in localhost it is showing:
Cannot GET /tokenPrice
I tried different method provided in moralis doc its working fine but I did same as the tutorial that throws me error:
const express = require("express");
const Moralis = require("moralis").default;
const { EvmChain } = require("#moralisweb3/common-evm-utils");
const app = express();
const cors = require("cors");
require("dotenv").config();
const port = 3001;
app.use(cors());
app.use(express.json());
app.get("./tokenPrice", async (req, res) => {
const { query } = req;
const responseOne = await Moralis.EvmApi.token.getTokenPrice({
address: query.addressOne,
});
const responseTwo = await Moralis.EvmApi.token.getTokenPrice({
address: query.addressTwo,
});
console.log(responseOne.raw);
console.log(responseTwo.raw);
return res.status(200).json({});
});
Moralis.start({
apiKey: process.env.MORALIS_KEY,
}).then(() => {
app.listen(port, () => {
console.log(`Listening for API Calls`);
});
});
also I want to know what does that {query} & addressOne means here as I've never declared any var like before in my code.
I want to know what {query} and addressOne is , whether express js property or moralis
want to know why and where error occured and solution to resolve.
For addressOne and addressTwo, those are the query parameters used in your request. If you check the video you can see him showcasing an example of how the request should look like:
http://localhost:3001/tokenPrice?addressOne=0x51491...cf986ca&addressTwo=0xdac17f...6994597
And use 2 addresses of the tokens you wish to get the price for. You can indeed extend the logic to use more addresses
In the video at minute 45:00 You can see how the code should look like. Please make sure you complete your code for it to work properly.

TypeError: bodyParser.json is not a function in nuxt.js

I have received an error message stating: TypeError: bodyParser.json is not a function. My nuxt.config.js file has the following details regarding bodyparser (I originally had const bodyParser = require('body-parser') but an error appeared telling me that I had to use 'import' instead of 'require' so I changed it to 'import('body-parser'):
const bodyParser = import('body-parser')
export default {
serverMiddleware: [
bodyParser.json(),
'~/api'
]
}
In my index.js file under the api folder, I have the following code:
const express = require('express')
const bodyParser = require('body-parser')
const router = express.Router()
const app = express()
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
})
router.post('/track-data', (req, res) => {
console.log('Stored data!', req.body.data)
res.status(200).json({ message: 'Success!' })
})
module.exports = {
path: '/api',
handler: router
}
Does anyone know how to get this to run? Everytime I enter 'npm run dev' in the terminal, I get the error 'TypeError: bodyParser.json is not a function'.
I had a slightly similar issue and could solve it with this code, first i imported express in the config file, before i did it like you, with bodyParser, but got a deprecated warning, then i use it in the api folder, in the index file, like so:
// nuxt.config.js
import express from 'express';
export default {
ssr: true,
.......,
.......,
serverMiddleware: [
express.json(),
// Api middleware
{ path: '/api', handler: '~/api/index.js' },
]
}
// ~/api/index.js
// Router setup for serverMiddleware
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request);
Object.setPrototypeOf(res, app.response);
req.res = res;
res.req = req;
next();
});
export default {
path: '/api',
handler: router
};
hope it helps ! 👍
I'm not familiar with nuxtjs specifically, but after looking at the nuxtjs module export docs it looks like your require inside your index.js should be a path to the file, rather than just the string body-parser which I have to imagine just gets processed something like an npm module if no path is supplied.
Additionally, at least in NodeJS and per the MDN docs on export and import, the syntax to import something that's exported with export default is import { destructuredModuleName } from 'string/representing/relative/or/absolute/path/to/module'
or
import * as whatYouWantToCallTheObject from 'string/representing/relative/or/absolute/path/to/module' would give you a more traditional module object with properties/methods matching properties on the exported module.
This should fix it:
import bodyParser from 'body-parser'
You actually used the import() as a dynamic import. It returned a promise which didn't have the json property. Therefore, the error was displayed.

let express.js redirect all sub-path of any html file path to itself

I have this code on file server.js:
const express = require('express');
const { join } = require('path');
const app = express();
app
.get(':path.html/*', (req, rep) => {
rep.sendFile(join(__dirname, req.params.path+'.html'));
})
.listen(8080)
I run it (node server.js) then when I visit
http://localhost:8080/foo.html/aaa or
http://localhost:8080/foo.html/bbb/ccc
I get the content of foo.html.
This works for any html file of ./*.html
I would like this works for any html file of ./**/*.html
For example when I visit http://localhost:8080/sub/dir/bar.html/foo I want to get content of sub/dir/bar.html
how to do that with express router syntax?

error hanlders not working properly in express together with nuxtjs

I am using Nuxtjs as a middleware in expressjs, and I have problems with handling errors in express server part.
When browser goes to 'localhost:3000', it will throw res.status is not a function error. when I comment that code block, everything is good expect that I cannot handle with uncaught server errors...
Any ideas?
import dotenv from 'dotenv'
dotenv.config({ silent: process.env.NODE_ENV === 'production', path: 'server/.env' })
import express from 'express'
import { ready } from 'consola'
import { Nuxt, Builder } from 'nuxt'
import cors from 'cors'
import { json, urlencoded } from 'body-parser'
import cookieParser from 'cookie-parser'
import passport from 'passport'
import './utils/auth'
import router from './routes'
const app = express()
app.use(json({ limit: '50mb' }))
app.use(urlencoded({ limit: '50mb', extended: true }))
app.use(cookieParser())
app.use(cors())
app.use(passport.initialize())
app.use('/api', router)
app.use('/api/*', (req, res) => {
res.status(404).end()
})
// error handlers
// it is problematic
// app.use((err, req, res) => {
// res.status(err.status || 500).end()
// })
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
const nuxt = new Nuxt(config)
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
app.use(nuxt.render)
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000
app.set('port', port)
app.listen(port, host)
ready({
message: `Server listening on http://${host}:${port}`,
badge: true,
})
}
start()
Without testing this code myself, I had a similar issue with my custom error handler and realized at one point I removed the next argument and it was failing. Can't say it will fix the issue because you are getting an error about res. I read through this page a few times and noticed a few mistakes I was making because I was using async functions.
Error Handling Guide may provide some help if you look over it carefully, but more specifically my comment about next is found under the title Writing error handlers
I wanted to say it might be arrow functions, but I don't see why that would break the logic here.

Is there a way to bootstrap an Express app?

I'm building an app in Express but I'd like it to call out to S3 to retrieve some keys before the server actually starts up. Is this possible in Express? If I google bootstrap Express I get hits for setting up Express with twitter Bootstrap.
I have used Sails.js before and you could specify bootstrap configurations in a bootstrap.js file so I guess I'm looking for something similar. Otherwise are there alternatives?
I have a index.js file and a separate bin/www file which calls the index.js file. I'd like the bootstrapping done in index.js so that it's included as part of the tests. Right now I 'initialize' the bootstrap but as it's asynchronous the server is already up and running before the bootstrap has complete (or errored out) i.e.
import express from 'express';
import {initializeFromS3} from './services/initializerService';
import healthCheckRouter from './routes/healthCheckRouter';
import bodyParser from 'body-parser';
initializeFromS3(); // Calls out to S3 and does some bootstrapping of configurations
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// ---------------------------- Routes ----------------------------
app.use('/', express.static('dist/client/'));
app.use('/health-check', healthCheckRouter);
export default app;
Posting my solution for anyone who comes across the same and has a mind blank. I kept the bin/www and index.js files separately but had the express object returned from index.js via a method. Solution below thanks to the friendly people of Github.
Index.js file:
import express from 'express';
import {initialize} from './services/appService';
import healthCheckRouter from './routes/healthCheckRouter';
import loginRouter from './routes/loginRouter';
export function getExpress() {
return initialize()
.then(() => {
const app = express();
// ---------------------------- Routes ----------------------------
app.use('/', express.static('dist/client/'));
app.use('/login', loginRouter);
app.use('/health-check', healthCheckRouter);
return app;
})
}
bin/www file:
import winston from 'winston';
import bodyParser from 'body-parser';
import {getExpress} from '../index';
getExpress()
.then(app => {
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
const port = 3002;
app.listen(port, () => {
winston.info(`Server listening on port ${port}!`);
});
})
.catch(err => {
winston.error('Error starting server', err);
});
Integration tests:
import request from 'supertest';
import {getExpress} from '../../index'
describe('/login integration test', () => {
let app = null;
beforeEach(done => {
getExpress()
.then(res => {
app = res;
done();
});
});
describe('GET /login', () => {
it('should return 400 error if \'app\' is not provided as a query string', done => {
request(app)
.get('/login')
.expect(400, done);
});
});
});