After executing the export, on the host, when I enter the link manually or refresh the page, a message is not displayed.
I have the server.js and the next module. Do I need to do anything else?
server.js
const express = require('express');
const next = require('next');
const { parse } = require('url');
const DEV = process.env.ENVIRONMENT !== 'production';
const PORT = 4567;
const app = next({dir: '.', dev: DEV});
const handle = app.getRequestHandler();
const getRoutes = require('./routes');
const routes = getRoutes();
app.prepare().then(() => {
const server = express();
server.get('*', (req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
const route = routes[pathname];
if (route) {
return app.render(req, res, route.page, route.query);
}
return handle(req, res);
});
server.listen(PORT, (err) => {
if (err) throw err;
console.log(`> READY FOR LIFOTFF http://localhost:${PORT}`);
});
});
Router.js
module.exports = () => {
return {
'/': { page: '/' },
'/404': { page: '/404' },
'/about-us': { page: '/about-us' },
}
}
next.config.js
const getRoutes = require('./routes');
module.exports = {
useFileSystemPublicRoutes: true,
exportPathMap: getRoutes
}
I add trailingSlash: true to next.config.js,it's working.
my new next.config:
const getRoutes = require('./routes');
module.exports = {
trailingSlash: true,
useFileSystemPublicRoutes: true,
exportPathMap: getRoutes,
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
Related
///index.js
const functions = require("firebase-functions");
const express = require("express");
const app = express();
const productRouter = require('./routes/productRoutes');
const globalErrorHandler = require('./controllers/errorController');
const AppError = require('./utils/appError');
// Compressing upcompressed files which is been sent to client such text.
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.send('Hello World')
});
app.get('/homepage', (req, res) => {
res.send('Hello People of God')
});
app.use('/products', productRouter);
// Handing Unhandled Routes
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});
app.use(globalErrorHandler);
exports.app = functions.https.onRequest(app);
///productRoutes.js
const express = require('express');
const {
getProduct,
getAllProduct,
} = require('./../controllers/productController');
const router = express.Router();
router
.route('/')
.get(getAllProduct);
router
.route('/:id')
.get(getProduct);
module.exports = router;
///productController.js
const AppError = require('../utils/appError');
const Product = require('../modals/productModels');
const catchAsync = require('../utils/catchAsync');
// GET SINGLE PRODUCT CONTROLLER
exports.getProduct = catchAsync(async (req, res, next) => {
const product = await Product.findById(req.params.id)
.populate('reviews');
if (!product) {
return next(new AppError('No product found with that ID', 404));
}
res.status(200).json({
status: 'success',
data: {
product
}
});
});
// GET ALL PRODUCT CONTROLLER
exports.getAllProduct = catchAsync(async (req, res, next) => {
const products = await Product.find();
res.status(200).json({
status: 'success',
results: products.length,
data: {
products
}
});
});
///server.js
const mongoose = require('mongoose');
const app = require('./index')
const dotenv = require('dotenv');
// CONNECTING TO MONGODB SERVER
dotenv.config({ path: './config.env' })
const DB = process.env.DATABASE.replace('<PASSWORD>', process.env.DATABASE_PASSWORD);
mongoose.connect(DB, {
useNewUrlParser: true,
safe: true,
strict: false,
useUnifiedTopology: true
}).then(con => console.log('DB connection successful'))
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
After running function serve on my terminal i can access the two '/' and 'homepage' app.get which return the res "Hello world" and "Hello people of God" but can't access app.use('/products', productRouter). Its does take some time to run and throw an error "{"code":"ECONNRESET"}" please why is this so.
Am expecting to get my list of products from my mongodb data base.
I'm trying to perform a simple .find() query on my mongodbAtlas, but the result of this query is an empty object.
this is my server file:
require("dotenv").config({ path: "./config.env" });
const { MongoClient, ServerApiVersion } = require("mongodb");
const express = require("express");
const { ServiceBroker } = require("moleculer");
const AUTH_SERVICE = require("./controller/services/auth/auth.service");
global.broker = new ServiceBroker({
nodeID: "auth",
});
const app = express();
app.use(express.json());
app.use("/auth", require("./routes/auth"));
const { PORT, URI } = process.env || 5000;
global.broker.createService(AUTH_SERVICE);
const start = async () => {
const dba = await MongoClient.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
global.db = dba.db("Auth");
try {
await dba.connect();
console.log("DATABASE CONNESSO CON SUCCESSO📡");
} catch (e) {
console.error(e);
}
await global.broker.start();
app.listen(PORT, () => console.log(`PORT IT'S UP AND RUNNING 🚀 ON ${PORT}`));
};
start();
this is my routes file:
const express = require("express");
const router = express.Router();
router.get("/register", async (req, res) => {
const data = global.db.collection("Users").find({}).toArray();
res.send(data);
});
module.exports = router;
this is how my document is populated:
{"_id":{"$oid":"6297bbc83a95b81d74882f65"},"username":"Test","email":"test#gmail.com","password":"1234"}
I think you are missing the "await" keyword after const data..... as API data fetching calls are asynchronous and required promise/ async-await to handle. Being async in nature, it moves forward to the next instruction and returns an empty array.
const express = require("express");
const router = express.Router();
router.get("/register", async (req, res) => {
const data = await global.db.collection("Users").find({}).toArray();
res.send(data);
});
module.exports = router;
I am building a MERN app and when I try to console.log(req.file) on the server I get undefined. I've checked the multer github page and other SO articles, but I still haven't been able to figure it out using React hooks and jsx. I'm newish to SO so, I will add edits since I can't comment yet.
Here is a link to the branch in GitHub if you want to see all the files. https://github.com/BenjDG/puzzle-gallery/tree/so
I'm new to multer and react so any help is appreciated.
Here is my code:
server\controllers\puzzleController.js
const multer = require('multer');
const upload = multer({ dest: './uploads'});
const db = require('../models');
const fs = require('fs');
const type = upload.single('picFile');
// Defining methods for the puzzleController
module.exports = {
findAll: function (req, res) {
db.Puzzle
.find(req.query)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
save: (type, function (req, res) {
// console.log(req);
console.log(req.file);
console.log(req.body);
res.sendStatus(200);
}),
remove: function (req, res) {
db.Puzzle
.findById({ _id: req.params.id })
.then(dbModel => dbModel.remove())
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
};
client\src\components\gallery\index.js
import React, { useState } from 'react';
import './styles.css';
import API from '../../services/API';
export default function Gallery () {
const [picFile, setPicFile] = useState();
const handleGetClick = async () => {
API.findAll()
.then(res => {
console.log(res)
})
.catch(err => console.error(err))
}
const handleUploadClick = async (e) => {
e.preventDefault();
// console.log(picFile);
// create new formData instance
const bodyFormData = new FormData();
// append single file to formData instance
bodyFormData.append('picFile', picFile.selectedFile);
// log items in formData object
for (const element of bodyFormData) {
console.log(element);
}
// send formData obj to axios function
API.save(bodyFormData)
.then(res => {
//console.log(res)
})
.catch(err => console.error(err))
}
const onFileChange = (e) => {
console.log(`e.target.files[0]`, e.target.files[0])
setPicFile({ selectedFile: e.target.files[0] });
}
return (
<div>
<h1>My Puzzle Gallery</h1>
<form encType='multipart/form-data'>
<input type='file' name='picFile' onChange={onFileChange} />
<br />
<br />
<button onClick={handleUploadClick}>Upload a picture</button>
</form>
<br />
<br />
<button onClick={handleGetClick}>Get pictures</button>
<br />
<br />
<img src='https://placekitten.com/640/360' alt='kitten' />
</div>
);
}
client\src\services\API.js
import axios from 'axios';
const API = {
login: (username, password) => {
const obj = {
username: username,
password: password
};
return axios.post('/api/auth/login', obj);
},
register: (username, password) => {
const obj = {
username: username,
password: password
};
return axios.post('/api/auth/register', obj);
},
logout: function () {
return axios.get('api/auth/logout');
},
save: function (form) {
return axios.post('api/puzzle/', form).catch(err=>console.error(err));
},
findAll: function () {
return axios.get('api/puzzle/');
},
}
export default API;
server\routes\api\puzzle\index.js
const router = require('express').Router();
const puzzleController = require('../../../controllers/puzzleController');
// Matches with '/api/puzzle'
router.route('/')
.get(puzzleController.findAll)
.post(puzzleController.save);
// Matches with '/api/books/:id'
router.route('/delete/:id')
.delete(puzzleController.remove);
module.exports = router;
server\server.js
const path = require('path');
const express = require('express');
const passport = require('./config/passport');
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const helmet = require('helmet');
const morgan = require('morgan');
const corsOptions = require('./config/cors.js');
const routes = require('./routes');
const { v1: uuidv1 } = require('uuid');
// console.log(uuidv1());
const PORT = process.env.PORT || 3001;
const app = express();
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/puzzlegallery', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
mongoose.set("useCreateIndex", true);
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(helmet({ contentSecurityPolicy: false }));
app.use(session({ secret: 'sassy', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors(corsOptions));
app.use(morgan('dev'));
app.use(routes);
// for Reactjs ##################
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
// #################################################
if (process.env.NODE_ENV === 'production') {
app.get('*', (_, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
}
app.listen(PORT, (err) => {
if (err) throw err;
console.log(
`🌎 Server is Ready and Listening on http://localhost:${PORT}`
); // eslint-disable-line no-console
});
EDIT:
This seemed to work. Thanks again!!
const path = require('path');
const router = require('express').Router();
const puzzleController = require('../../../controllers/puzzleController');
const multer = require('multer');
const { v1: uuidv1 } = require('uuid');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../../../../tmp/my-uploads'))
},
filename: function (req, file, cb) {
cb(null, uuidv1())
}
})
const upload = multer({ storage: storage });
// Matches with '/api/puzzle'
router.route('/')
.get(puzzleController.findAll)
// Matches with '/api/books/:id'
router.route('/delete/:id')
.delete(puzzleController.remove);
router.use(upload.single('picFile'));
router.route('/')
.post(puzzleController.save);
module.exports = router;
you cannot call the middleware inside the save function like this.
I cloned your repo and added the following code in server.js and it's working fine and I got the value in the req.file.
const multer = require('multer');
const upload = multer({ dest: 'uploads/'});
app.post('/api/puzzle/', upload.single('pictureFile'),(req,res,next)=>{
console.log("req.file22222222", req.file);
})
I am creating a sveltejs/sapper app. I am trying to post some info from the frontend to the backend express server using axios in the script tag. Although get requests from external sources are succeeding, axios is throwing a 404 error while posting to the express route. Refer these images posted below.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
import sirv from 'sirv';
import * as sapper from '#sapper/server';
const app = express();
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
app.use(
sirv('static', {dev}),
sapper.middleware(),
bodyParser.json(),
bodyParser.urlencoded({extended:true})
);
app.post('/task', (req, res) => {
res.sendStatus(200);
console.log(req.body);
// fs.writeFile(`./downloads/${req.body.file}`, req.body.buffer, (err) => {
// if (err) throw err;
// console.log(`${res.file} downloaded to backend server`);
// });
});
app.listen(PORT, err => {
if (err) console.log('error', err);
});
frontend script
<script>
//variables
let start = false;
let url = '';
let filename = '';
let downloadProgress = 0;
let error = false;
let progressBarStyle = 'bg-success';
//automated Events
$:downloadLabel = downloadProgress.toString();
$:if(downloadLabel == '100') {
progressBarStyle = 'bg-warning';
downloadLabel = 'DOWNLOAD COMPLETE! FILE WILL BE TRANSFERED SHORTLY!';
}
//axios config
let config = {
onDownloadProgress: progressEvent => {
downloadProgress = Math.floor((progressEvent.loaded * 100) / progressEvent.total); }
}
//functions
function startDownload() {
start = true;
axios.get(url, config).then((res) => {
if(res.status == 200) {
let data = {
file: filename,
buffer: res.data
}
axios.post('/task', data).then(() => {
console.log('Data sent to server');
}).catch((err) => {
console.log(err);
});
}
else {
error = true;
}
}).catch((err) => {
error = true;
});
}
function reset() {
// start = false;
// url = '';
// filename = '';
// downloadProgress = 0;
window.location.reload();
}
</script>
browser console
network tab
You use sapper,
Try to read docs.
example:
const express = require('express');
import sirv from 'sirv';
import compression from 'compression';
import * as sapper from '#sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const app = express();
app
/* add your handlers here */
.post('/task', (req, res, next) => {
res.sendStatus(200);
console.log(req.body);
})
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
I find here solution
You have to send something in the request handler:
(req, res) => {
res.sendStatus(200);
}
I have a working codebase where they have already setup node proxy and jwt.
my server is running at 1010 port
but when I hit this url http://localhost:1010/sampletest
I am getting an error in the browser screen Cannot GET /sampletest
even I hit this url http://localhost:1010/jump/api/v1 but still I am getting same error
can you tell me how to fix it or am I missing anthing in the configurations
providing my index.js and server.js code below
sports.js
const express = require('express');
const axios = require('axios');
const mime = require('mime-types');
const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');
const AppConstants = require('../../../constants/AppConstants');
const credentials = require('../../../internals/credentials.json');
const memberGroupingHelper = require('../../helpers/rank/memberGrouping');
const exportHelper = require('../../helpers/rank/rankExportHelper');
const formatExportData = require('../../helpers/rank/formatExportData');
const rankCommonHelper = require('../../helpers/rank/rankCommonHelper');
const rankProvDataHelper = require('../../helpers/group/getProvData');
//const aggregateHelper = require('../../helpers/group/aggregateFilter');
const { rankAggregatelastrsApi } = require('jump-svc-utils');
//router.get('/:searchMode/:lastrSearch', (req, res, next) => {
router.get('/sampletest', (req, res, next) => {
const { originalUrl } = req;
//console.log(" originalUrl ", originalUrl);
const mode = req.params.searchMode;
const value = encodeURIComponent(req.params.lastrSearch);
console.log("document 40--->", mode);
console.log("for document Testing0--->", mode);
const url = `/jkjkjk/sdjksdjkjksdjksd/sdklsdlksdklsdkl`;
axios.get(AppConstants.GET_JWT_TOKEN_URL, {
auth: {
username: credentials.auth.racfId, password: credentials.auth.password
}
})
.then((jwtResponse) => {
// var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
var jwtToken = `Bearer 787878bjhbnmnmmwqdqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqw`;
axios.get(url, { headers: { "Authorization": jwtToken } })
.then((response) => {
console.log("document then0--->", response);
const file = Buffer.from(response.data.content, 'base64');
const fileType = mime.contentType(response.data.contentInfo.fileType);
const fileExtension = response.data.contentInfo.fileType.toLowerCase();
const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
res.set('Content-Type', fileType);
res.set('Content-disposition', `attachment; ${fileName}`);
res.send(file);
})
.catch((e) => {
console.log("e catch document0--->", e);
console.log("e.message catch document0--->", e.message);
console.log("catch document--->", e.response);
if (e.response) {
return res.status(e.response.status).send(e.response.data);
}
res.status(500).send(e.message || 'Something wrong');
});
});
ResponseUtil.callService(res, url);
});
module.exports = router;
index.js
const express = require('express')
const app = express()
const port = 1010
const jumpServices = require('./services/jump');
const compression = require('compression');
var BodyParser = require('body-parser');
const glob = require('glob');
const path = require('path');
app.use('/jump/api/v1', jumpServices);
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({
extended: true
}));
//app.use(compress())
// app.use(compression());
// include all the controllers
const controllers = glob.sync(path.join(__dirname, '/controllers/**/*.js'));
console.log("controllers--->", controllers);
controllers.forEach((controllerFileName) => {
require(controllerFileName)(app); //eslint-disable-line
});
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
I don't see any calls registering your sub Routers with the top level express application. You should need to call app.use for each of your sub routers.