When I make the request post on page of login I receive this error:
Error: getaddrinfo ENOTFOUND bluebirdpages.olk.com
But this just happens in production in localhost works, I dont know why..
My code:
const express = require('express');
const bodyParser = require('body-parser');
const logger = require('morgan');
const http = require('http');
const path = require('path');
const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 8000;
const server = http.createServer(app);
var options = {
host: 'bluebirdpages.olk.net/',
path: '/login',
method: 'POST'
}
http.request(options, callback);
app.use(express.static(path.join(__dirname, 'client/build')));
require('./server/routes')(app);
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome'
}));
server.listen(port);
module.exports = app;
Someone know why? and could help me? Please..
Related
GET request return 404 error but POST request to the same url works fine I could not figure out the reason.
this is the server setup:
images.route.js
const express= require('express');
const controllers = require('./controllers');
const router= express.Router();
const upload = require('../../lib/uploads.controller');
router.get('/', (req, res)=> res.send('get request'))
router.post('/', controllers.getAll);
module.exports= router;
route.js
const express = require('express'),
router = express.Router();
const albumRoutes = require('./albums/album.route');
const imageRoutes= require('./images/index');
router.use('/albums', albumRoutes);
router.use('/images', imageRoutes);
module.exports= router;
server.js
let express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser');
let history = require('connect-history-api-fallback');
const userRoute = require('./routes/router');
const app = express();
app.options('*', cors())
app.use(cors());
app.use(history());
app.use(express.json({limit:
'50mb'}));
app.use(express.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 1000000
}));
app.use('/api', userRoute)
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log('Connected to port ' + port)
})
I have been searching for a solution but I could not find any reason.
I even installed different REST API apps like postman and insomnia just in case, but it is the same
I recently went about restructuring an application I am building to fit the service oriented architecture. I really liked the way a certain tutorial structured his code, so I was trying to replecate a similiar strucutre in my app.
I want to abstract all my middleware out of app.js in my root so that basically all my app.js folder does is configure my express app. I would like to abstract all my middleware out of app.js, and configure it in my index.js folder located in my server directory. You can check my github repo below.
Please check the example repo, I would like to set up my code like this but am having lots of difficulty. Every time I try and take the middleware out of app and run it by requiring into index my app breaks.
Github Repo
I am trying to structure my code like so.
Example Repo
App.js (located in root)
const express = require('express');
const app = require('./server/index');
const mongoose = require('mongoose');
const passport = require('passport');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT || 3000;
require('./server/config/passport')(passport);
// DB Config
const db = process.env.MongoURI;
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {console.log('MONGODB Connected')})
.catch(err => console.log(err))
app.listen(port, () => {
console.log(`Running on port ${port}`);
});
index.js (located in server directory)
const express = require('express');
const app = express();
const api = require('./api/api');
const indexRouter = require('./api/index/indexRouter');
const usersRouter = require('../server/api/user/userRoutes');
require('./middleware/appMiddleware')(app);
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
appMiddleware.js (located in middleware directory which is inside server directory)
const createError = require('http-errors');
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const dotenv = require('dotenv');
dotenv.config();
module.exports = function(app) {
app.use(expressLayouts);
app.set('views', path.join(__dirname, '../../views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
})
};
Terminal Error
Error: Failed to lookup view "error" in views directory "/Users/jojovera/Documents/fantasyfootball/views"
at Function.render (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/application.js:580:17)
at ServerResponse.render (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/response.js:1008:7)
at ServerResponse.res.render (/Users/jojovera/Documents/fantasyfootball/node_modules/express-ejs-layouts/lib/express-layouts.js:77:18)
at /Users/jojovera/Documents/fantasyfootball/server/middleware/appMiddleware.js:55:7
at Layer.handle_error (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:315:13)
at /Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:335:12)
at next (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:275:10)
at /Users/jojovera/Documents/fantasyfootball/server/middleware/appMiddleware.js:44:3
at Layer.handle [as handle_request] (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:317:13)
at /Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:335:12)
at next (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:275:10)
at /Users/jojovera/Documents/fantasyfootball/server/middleware/appMiddleware.js:39:3
So, I got this error while try to ready my application for production. So, my index.js code is
const app = express();
const port = 8000;
const cors = require('cors');
const db=require('./config/mongoose');
const path = require('path')
//library used
const passport = require('passport');
const passportJWT = require('./config/passport-jwt-strategy');
const bcrypt = require('bcrypt');
//middleware
app.use(express.json());
app.use(cors());
//use routes
app.use('/', require('./routes'));
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) =>
res.sendFile(path.join(__dirname, 'frontend', 'build', 'index.html')))
app.listen(port, async function(err){
if(err){
console.log(`error in running of server;${err}`);
}
console.log(`server is running on port:${port}`);
});
This is my file structure. So, If someone know, why this is happening. please reply.
Thanks
express js the body undefined error
I shared the files below. I got very angry. No error appears. Please help me.
Although I do it again I get the same error
I searched a lot but none of the solutions worked.
main.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res)=>{
res.render('site/index')
})
router.get('/login', (req,res)=>{
res.render('site/login')
})
router.get('/register', (req,res)=>{
res.render('site/register')
})
router.get('/postcreate', (req,res)=>{
res.render('site/postcreatepage')
})
router.get('/postupdate', (req,res)=>{
res.render('site/postupdatepage')
})
router.post('/post/post', (req,res)=>{
console.log(req.body)
})
module.exports = router
I checked and searched many times could not solve
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
app.use('/', main)
app.use(express.static('static'))
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.listen(port, hostname, ()=> console.log(`Example app listening on port http://${hostname}:${port}/`))
Although I do it again I get the same error
html
<html>
<head>
</head>
<body>
<form action="post/post" method="post">
<input name="title"><br>
<input name="content"><br>
<button type="submit">But</button>
</form>
</body>
</html>
In your route, you have to return a response other wise the request will hang:
main.js
router.post('/post/post', (req,res)=>{
console.log(req.body)
const resObject = {
... do something with req.body ...
};
return res.status(201).json(resObject);
});
In your app entrypoint, set your routes after your config and middleware:
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
/* config */
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
/* Middleware */
app.use(express.static('static'))
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
/* Routes */
app.use('/', main)
app.listen(port, hostname, () => console.log(`Example app listening on port http://${hostname}:${port}/`)
I get next error when trying open http://localhost:5000/
Error:
ENOENT: no such file or directory, stat
'C:\Users\Andriixyz\Desktop\chat- node\chat\client\build\index.html'
const path = require("path");
const port = process.env.PORT || 5000;
const express = require("express");
const app = express();
const server = app.listen(port);
var io = require("socket.io").listen(server);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("client"));
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/build/index.html"));
});