I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
router.js
router.post('/schedule/entry', function(req,res){
console.log(req.file.name);
});
Console return me undefined name, if I write this code
router.post('/schedule/entry', function(req,res){
console.log(req.file);
});
Return 'undefined'
Why?
package.json
{
"name": "nodejs-rest-api-authentication",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.16.1",
"csv-array": "0.0.22",
"csv-write-stream": "^2.0.0",
"express": "^4.14.1",
"express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
}
}
server.js
const app = require('./app');
const port = process.env.PORT || 3000;
const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});
screenshots
screenshots
codeGit
Based on the discussion in the comment section:
const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js
app.post('/', (req, res) =>{
var form = new formidable.IncomingForm()
form.multiples = true
form.keepExtensions = true
form.uploadDir = uploadDir
form.parse(req, (err, fields, files) => {
if (err) return res.status(500).json({ error: err })
res.status(200).json({ uploaded: true })
})
form.on('fileBegin', function (name, file) {
const [fileName, fileExt] = file.name.split('.')
file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
})
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Attached Screenshots:
Because of body-parser middleware file will be not available in req so you must use another middleware libraries like connect-busboy or multer or connect-multiparty
Related
My express app works fine on the localhost but it does not work on Heroku.
When I added a line it stops working and
the line is
app.use("/api/product", require("./routes/product"))
Here is the code
Index.js
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.get("/", (req, res) => {
res.send("responded")
});
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
product.js
const express = require("express");
const router = express.Router();
router.get("/", async (req, res) => {
try {
res.json({
status: 200,
message: "Data has been successfully fetched"
});
}
catch (error) {
console.log(error);
return res.status(400).send("server error")
}
})
module.exports = router;
package.json
{
"name": "backend-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.3"
}
}
Folder structure
You would wanna switch your route handlers place. Otherwise you will never rich your api, as the first catches all requests.
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.get("/", (req, res) => {
res.send("responded")
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
I am making a MERN app and having some problems with connecting/running node and react server together.
Root package.json
{
"name": "server",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "nodemon server/server",
"client": "npm start --prefix client",
"dev": "concurrently \"npm start\" \"npm run client\""
},
"dependencies": {
"async": "^3.2.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"dotenv": "^10.0.0",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"mongoose": "^5.13.0",
"morgan": "~1.9.1",
"populatedb": "^1.0.0"
},
"devDependencies": {
"concurrently": "^6.2.0",
"nodemon": "^2.0.8"
}
}
Client proxy:
"proxy": "http://127.0.0.1:5000",
"secure": false
Main server file:
require('dotenv').config();
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose = require('mongoose');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// set up mongoose connection
const mongoDB = process.env.DB_STRING;
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:' ));
console.log('Connected');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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('/', indexRouter);
app.use('/users', usersRouter);
if(process.env.NODE_ENV !== 'development') {
app.get('*', function (req, res) {
res.sendFile(path.resolve(__dirname, 'client/build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000
//Express js listen method to run project on http://localhost:5000
app.listen(PORT, console.log(`App is running in ${process.env.NODE_ENV} mode on port ${PORT}`))
// 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');
});
module.exports = app;
I am using 'npm run dev' command to start the server.
I am getting an error message "proxy error: could not proxy request /users from localhost:3000 to http://127.0.0.1:5000".
I have tried changing proxy to 0.0.0 and also changed the scripts file to:
"start": "node ./bin/www",
"devstart": "nodemon ./bin/www",
"client": "npm start --prefix client",
"dev": "concurrently \"npm start\" \"npm run client\""
but it still does not work. I have tried some other solutions I've found but just can't get it right.
Here is also my test react file:
import React, { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [users, setUsers] = useState([]);
const getData = async () => {
const res = await axios.get("/users");
setUsers(res.data);
};
useEffect(() => {
getData();
}, []);
return (
<div>
{users.map((u) => (
<h4 key={u._id}>userName : {u.full_name}</h4>
))}
</div>
);
};
export default App;
Here is also my folder structure, if it is relevant by any chance
After trying some more solutions to fix the problem, what worked is:
in one terminal tab run nodemon app.js
in second terminal tab run npm start --prefix client.
There is probably something wrong with concurrently module, since this is working.
i have a problem, which when im trying to run my localhost/5000 its not working. I cant also get and post data on postman because of that. Anyone has an idea of how i can fix this ? However when i run the code it is showing that it is connected to my DB. I have also create an env file with the DB link and set the PORT to 5000
Here is the code:
server.js
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const PORT = process.env.PORT || 5000
const app = express();
app.use(express.json())
app.use(cookieParser())
app.use(cors)
app.use(fileUpload({
useTempFiles: true
}))
//connect to db
const URI = process.env.MONGO_URL
mongoose.connect(URI,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser:true,
useUnifiedTopology:true
}, err=> {
if (err) throw err;
console.log('Connected to Mongo DB')
})
// app.get('/', (req, res) => {
// res.json({msg: "Welcome"})
// })
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
app.use('/user', require('./routes/userRouter'))
package.json
{
"name": "Webapp",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.0",
"cloudinary": "^1.23.0",
"concurrently": "^5.3.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-fileupload": "^1.2.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.12"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
app.listen() should be at end of file, after app.use()
Just use localhost:5000 instead of localhost/5000 for url
I have been working with another developer and we have been able to deploy the React + Node.js application using Express to Heroku, however we are still receiving an error as shown below in the screenshot.
I am apparently getting a 404 from the server and I feel that we are close to resolving the problem; we just do not know if it is a simple syntax fix or structure in general.
Here is my root package.json file:
{
"name": "dev-personal-portfolio-2",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon index.js",
"test": "echo \"Error: no test specified \" && exit 1",
"post-build": "cd client && npm i && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"#sendgrid/mail": "^7.2.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.4"
}
}
Here is the server.js file:
require ('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const buildPath = ('build/index.html');
const port = process.env.PORT || 5000;
const sendGrid = require('#sendgrid/mail');
const server = express();
server.use(bodyParser.json());
server.use(cors());
// server.use((req, res, next) => {
// res.setHeader('Access-Control-Allow-Origin', '*');
// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
// res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// next();
// });
// server.get('/api', (req, res, next) => {
// res.send('API Status: Running')
// });
server.use(express.static('client/build'));
// server.use('/static', express.static('public'))
// server.use(express.static(path.resolve(__dirname, './public')));
// server.get('*', (req, res) => {
// res.sendFile(path.resolve(__dirname, 'index.html'));
// });
console.log(express.static('client/build'));
console.log(`${__dirname}/public/index.html`);
server.use(express.json());
const REACT_APP_SENDGRID_API_KEY =`${process.env.REACT_APP_SENDGRID_API_KEY}`
server.post('/api/email', (req, res, next) => {
sendGrid.setApiKey(REACT_APP_SENDGRID_API_KEY);
console.log(req.body);
const msg = {
to: 'kevgill95#gmail.com',
from: req.body.email,
subject: req.body.subject,
text: req.body.message
}
sendGrid.send(msg)
.then(result => {
res.status(200).json({
success: true
});
})
.catch(err => {
console.log('error: ', err);
res.status(401).json({
success: false
})
})
});
server.listen(port, () => {
console.log(`Server is up on port ${port}!`);
});
NOTE: for the console.logs, here is what is returning from them:
console.log(express.static('client/build'));
[Function: serveStatic]
console.log(${__dirname}/public/index.html);
/Users/kevingillooly/dev-personal-portfolio-2/public/index.html
We have tried commenting out lines of code as well to try to resolve the problem, but we have not encountered anything that works.
If anyone would know what the problem would be, that would be awesome. The build succeeds just fine however the problem is very vague and we have tried a lot of different methods.
I am new to node js and following a tutorial on scotch.io. I've imported morgan for logging requests, but when I run the code I get TypeError: app.use is not a function. This is my code for app.js;
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to deep thinking.'
}));
module.exports = app;
And for package.json:
{
"name": "postgres-express-react-node-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "nodemon ./bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.3",
"morgan": "^1.9.1"
},
"devDependencies": {
"nodemon": "^1.18.4"
}
}
require('express') returns a function, which you should call in order to get the express application. Therefore:
const app = express;
should be changed to:
const app = express();
Try this, change app=express; to app=express();
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express(); // changed this line
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to deep thinking.'
}));
module.exports = app;