I have a problem with code actually server not receives JSON or receives JSON as text
.......................................................................
.......................................................................
.......................................................................
app.js:
const config = require("config");
const express = require('express')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json()) //express.json was tried
app.use(bodyParser.text()) // if do not using this json null
app.use('/api/auth',require("./routes/auth.route"))
auth.route.js
const {Router} = require("express");
const config = require("config");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const {body,validationResult} = require("express-validator");
const User = require("../models/User");
const router = Router();
//api / auth/register
router.post(
'/register',
[
body("email",'Wrong Email').notEmpty().isEmail(),
// check('password','Min Char count is 6, Password incorrect').isLength({min:6})
],
async (req,res)=>{
console.log("body",req.body)
console.log("email",req.body['email'])
req.body = JSON.parse(req.body);
console.log("body",req.body)
console.log("email",req.body['email'])
const validationErrors = validationResult(req);
console.log(validationErrors.array())
if(!validationErrors.isEmpty())
return res.status(401).json({arguments: validationErrors.array(),type:"wrongInputData"});
console.log(2)
})
and client:
import {useState, useCallback} from 'react';
const urlStart = "http://localhost:5000";
export const useHttp = () =>{
const [loadings,setLoading] = useState(false);
const [setError] = useState(null);
const request =useCallback(async (url, method = 'GET',body = null) =>{
setLoading(true);
try {
if(body) {
body = JSON.stringify(body);
}
url = urlStart+url
const response = await fetch(url,{method: method, body: body,
headers: {'Content-Type': 'application/json'},
mode:'no-cors',cache: 'no-cache',});
const data = await response.json();
if(!response.ok){
throw new Error("Smth wrong : "+data?.message);
}
setLoading(false);
return data;
}catch (e) {
setLoading(false);
setError(e.message);
throw e;
}
},[]);
const clearError = () => setError(null);
return { loadings, request,clearError}
}
Related
I am trying to upload a file to the API, sort the numbers and then return the result in another text file that is available to download. I upload the file, and when I start the calculation I get the Internal Server Error. The API is running on port 3000 and I start the React App.js on port 3001.
Is there something I'm doing wrong?
This is the API's app.js:
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.use(bodyParser.text({ type: 'text/plain' }));
app.post('/sort', upload.single('inputFile'), (req, res) => {
console.log(req.file)
const input = req.file.buffer.toString().split('\n').map(Number);
const result = input.sort((a, b) => b - a);
const resultText = result.join('\n');
fs.writeFile('result.txt', resultText, (err) => {
if(err) throw err;
res.send('File succesfully sorted!');
});
res.set('Content-Type', 'text/plain');
res.send(resultText);
});
app.listen(3000, () => {
console.log('API is listening on port 3000');
});
This is the React App.js:
const [inputFile, setInputFile] = useState(null);
const [result, setResult] = useState(null);
const [processingTime, setProcessingTime] = useState(null);
const handleFileUpload = (event) => {
setInputFile(event.target.files[0]);
};
const startCalculation = async (event) => {
event.preventDefault();
const startTime = performance.now();
const formData = new FormData();
formData.append('inputFile', inputFile);
console.log(inputFile)
const response = await fetch("http://localhost:3000/sort", {
method: 'POST',
body: formData,
mode: 'no-cors',
});
const data = await response.text();
console.log(data);
setResult(data);
setProcessingTime(performance.now() - startTime);
};
const handleDownload = (event) => {
event.preventDefault();
const file = new Blob([result], {
type: 'text/plain'
});
const fileURL = URL.createObjectURL(file);
const link = document.createElement('a');
link.href = fileURL;
link.download = 'result.txt';
link.click();
};
The issue is on the client you are setting the input name to inputFile, however, on the backend you are telling Multer that the input name is myFile.
Change from this:
upload.single("myFile")
To this:
upload.single("inputFile")
I am trying to build a web application using MVC pattern, but I have a problem with POST-request to "http://localhost:5000/api/device": postman POST request attempt
The problem only occurs on POST request, GET request is OK: get request
Code:
index.js
const express = require('express')
const sequelize = require('./db')
require('dotenv').config();
const path = require('path')
const models = require('./models/models')
const cors = require("cors")
const app = express();
const router = require('./routes/index')
const fileUpload = require('express-fileupload')
const errorHandler = require('./milddleware/ErrorHandlingMiddleware')
app.use(cors())
app.use(express.json())
app.use(express.static(path.resolve(__dirname, 'static')))
app.use(fileUpload({}))
app.use('/api', router)
app.use(errorHandler)
const PORT = process.env.PORT || 5000;
const db_start = async ()=>
{
try
{
await sequelize.authenticate();
await sequelize.sync();
app.listen(PORT, ()=>{console.log(`Server started on port ${PORT}`)})
}
catch (e)
{
console.log(e);
}
}
db_start()
routes/index.js
const Router = require('express')
const router = new Router();
const deviceRouter = require('./deviceRouter')
const typeRouter = require('./typeRouter')
const brandRouter = require('./brandRouter')
const userRouter = require('./userRouter')
router.use('/user', userRouter)
router.use('/device', deviceRouter)
router.use('/brand', brandRouter)
router.use('/type', typeRouter)
module.exports = router
routes/deviceRouter.js
const Router = require('express')
const DeviceController = require('../controllers/deviceController')
const router = new Router();
router.post('/', DeviceController.create)
router.get('/', DeviceController.getAll)
router.get('/:id', DeviceController.getOne)
module.exports = router
controllers\deviceController.js
const uuid = require('uuid')
const path = require('path')
const {Device} = require('../models/models')
const ApiError = require("../errors/ApiError")
class DeviceController
{
async create(req, res, next)
{
console.log(req);
try{
const {name, price, brandId, typeId, info} = req.body;
const {img} = req.files;
let fileName = uuid.v4() + ".jpg";
img.mv(path.resolve(__dirname, '..', 'static', fileName));
const device = await Device.create({name, price, brandId, typeId, img: fileName});
return res.json(device);
}
catch(e)
{
next(ApiError.badRequest(e.message));
}
}
async getAll(req, res)
{
const {brandId, typeId} = req.query
let devices;
if(!brandId && !typeId)
{
devices = await Device.findAll()
}
if(brandId && !typeId)
{
devices = await Device.findAll({where: {brandId}})
}
if(!brandId && typeId)
{
devices = await Device.findAll({where: {typeId}})
}
if(brandId && typeId)
{
devices = await Device.findAll({where: {brandId,typeId}})
}
return res.json(devices)
}
async getOne(req,res)
{
}
}
module.exports = new DeviceController()
I logged the request and saw that the request body came up empty and req.files is undefined.
I compared these router and controller with others and found no differences in structure.
What am I doing wrong?
You cannot retrieve files of form-data directly from req.files.
Use formidable (it's an npm package) to parse form-data and work with it easily. Here are the steps:
Run npm install formidable.
Import formidable and fs package in your controller script with:
const formidable = require('formidable')
const fs = require('fs');
Change your create function with this:
async create(req, res, next) {
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req, async (err, fields, files) => {
// console.log('err', err)
// console.log('fields', fields)
if (err) {
next(ApiError.badRequest(err));
return;
}
const { name, price, brandId, typeId, info } = fields; // <-- fields contain all your text data. it's like req.body
const { img } = files; // <-- it should work now!
let fileName = uuid.v4() + ".jpg";
fs.writeFileSync(path.resolve(__dirname, '..', 'static', fileName), img);
const device = await Device.create({ name, price, brandId, typeId, img: fileName });
return res.json(device);
}
}
i have a problem if you can help,
i've deployed my app on heroku and it's working properly on localhost when i upload product picture when launching on localhost everything is working and the picture is added to my public folder and the url is passed to my Product image url field, but when doing the same on heroku deployed app it shows: "ENOENT: no such file or directory, open 'public/obNHUnF85G2kHtApYvix5D-1200-80-1617359184714.png"
thx in advance
Here is my app.js
const express = require('express')
const morgan = require('morgan')
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken');
var cors = require('cors')
const errorHandler = require('./middleware/error')
const app = express()
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions))
app.use(express.static('public'))
app.use(express.json())
app.use(morgan('tiny'))
require('dotenv/config')
const productRouter = require('./Routes/ProductRouter')
const categoryRouter = require('./Routes/CategoryRouter');
const authRoute = require('./Routes/auth');
const userRoute = require('./Routes/user');
const OrderRouter = require('./Routes/OrderRouter');
const imagesRouter = require('./Routes/addImagesRoute');
const { static } = require('express');
const apiUrl = process.env.API_URL
const port = process.env.PORT;
mongoose
.connect(process.env.CONNECTION_STRING, {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => {
console.log('connected successfully')
})
.catch(err => {
console.log(err)
})
app.use(`${apiUrl}/products`, productRouter)
app.use(`${apiUrl}/categories`, categoryRouter)
app.use(`${apiUrl}/auth`, authRoute)
app.use(`${apiUrl}/users`, userRoute)
app.use(`${apiUrl}/orders`, OrderRouter)
app.use(`${apiUrl}/images`, imagesRouter)
app.use(errorHandler);
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
My Uploading Router
const express = require('express')
const { uploadImage, uploadGalleryImages } = require('../controllers/uploadController')
const { authorize, protect } = require('../middleware/auth')
const uploadRouter = express.Router()
const multer = require('multer')
const path = require('path')
const FILE_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpeg',
'image/jpg': 'jpg'
}
const storage = multer.diskStorage({
destination: function(req, file, cb) {
const isValid = FILE_TYPE_MAP[file.mimetype]
let uploadError = new Error('invalid image type')
if (isValid) {
uploadError = null
}
cb(uploadError, 'public/')
},
filename: function(req, file, cb) {
const fileName = file.originalname.split(' ').join('-')
const extension = FILE_TYPE_MAP[file.mimetype]
cb(null, `${fileName.split('.', 1)}-${Date.now()}${path.extname(file.originalname)}`)
}
})
const uploadOptions = multer({ storage: storage })
uploadRouter.use(protect)
uploadRouter.use(authorize('publisher', 'admin'))
uploadRouter.post(
'/:productId/image',
uploadOptions.single('image'),
uploadImage
);
uploadRouter.put('/:productId/images', uploadOptions.array('images', 8), uploadGalleryImages);
module.exports = uploadRouter;
Adding url and hash function
const file = req.file
if (!file) return res.status(400).send('No image in the request')
const fileName = file.filename
const basePath = `${req.protocol}://${req.get('host')}/`
try {
const product = await Product.findByIdAndUpdate(
req.params.productId, {
imageUrl: `${basePath}${file.filename.split('.', 1)}${path.extname(
file.originalname
)}`
}, { new: true }
);
await product.save();
const url = product.imageUrl;
const hash = await handler(url.toString());
const hashString = JSON.parse(hash).blurHash;
await Product.findByIdAndUpdate(req.params.productId, {
imageHash: hashString
}, { new: true })
product.save()
res.send(product)
} catch (error) {
return next(new ErrorResponse(`an error occured : ${error}`, 400))
}
})```
when i upload on localhost [Local host request and result][1]
when i upload on heroku server [Heroku][2]
[1]: https://i.stack.imgur.com/Fp8OK.png
[2]: https://i.stack.imgur.com/oaFuC.png
I have making an API using express and node.
Here is my app.js
const express = require('express');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
// setup dotenv to read environment variables
dotenv.config()
// Load Environment Varibles
const env = require('./utils/env');
// INIT MONGODB CONNECTION
require('./mongoose');
// create a new express application
const app = express();
// setup bodyparser middleware to read request body in requests
// we're only reading JSON inputs
app.use(bodyParser.json());
// Listen to API routes
const apiRoutes = require('./routes')
app.use('/api', apiRoutes);
// Start listening to requests
app.listen(env.PORT, () => {
console.log(`Server started on PORT ${env.PORT}`);
});
And here is the API routes that are being imported
const express = require('express');
const apiController = require('./apiController');
const apiValidator = require('./apiValidator');
const router = express.Router();
router.post('/login', apiValidator.loginUserValidator, apiController.loginUserController);
router.get('/rand', (req, res) => {
res.send('Some randon text');
});
module.exports = router;
Here is the middleware
const {
failureResponse
} = require('./../utils/response');
const errorcodes = require('./../utils/errorcodes');
const loginUserValidator = (req, res, next) => {
const user = req.body;
if (!user.username) {
return res.status(400).json(failureResponse(errorcodes.ERROR_INVALID_BODY_PARAMETER, "Invalid username"));
}
if (!user.password) {
return res.status(400).json(failureResponse(errorcodes.ERROR_INVALID_BODY_PARAMETER, "Invalid password"));
}
if (user.authTokens) {
delete user.authTokens;
}
next();
};
module.exports = {
loginUserValidator
};
Here is the controller
const User = require('./../models/user');
const {
successResponse,
failureResponse
} = require('./../utils/response');
const errorcodes = require('./../utils/errorcodes');
const loginUserController = async (req, res) => {
try {
const user = req.body;
// find if the user already exists
const existingUser = await User.findOne({
username: user.username
});
if (existingUser) {
// user exists. generate token and login user
console.log('Existing user login');
const token = existingUser.generateAuthToken();
return res.status(200).json(successResponse(token));
} else {
console.log('New user login');
const savedUser = await new User(user).save();
const token = savedUser.generateAuthToken();
return res.status(200).json(successResponse(token));
}
} catch (e) {
console.log(e);
return res.status(400).json(failureResponse(errorcodes.ERROR_SERVER_ERROR, "Unable to login user"));
}
};
module.exports = {
loginUserController
};
Here the issue is when I try to hit the login route from Postman, I am getting an error which says Could not get any response.
But when I hit the rand route, the output is correct.
So the issue isn't the arrangement of the code.
Why am I not able to use the login route here?
This is what I want, server is a file server, when client asks for certain file, it'll stream that file back. Instead of koi-static, I try to do this, but the dest.jpg only contains 'Not found'.
client code:
var Koa = require('koa');
var Router = require('koa-router');
const HttpStatus = require('http-status');
const fs = require('fs');
const koaBody = require('koa-body');
const request = require('request');
const tempSaveFile = fs.createWriteStream('dest.jpg');
const writeStream = request.post('http://localhost:3456/getfile/src.jpg').pipe(tempSaveFile);
writeStream.on('finish', () => {
tempSaveFile.end();
console.log('Upload successful! ');
});
server code:
var Koa = require('koa');
var Router = require('koa-router');
const HttpStatus = require('http-status');
const fs = require('fs');
const koaBody = require('koa-body');
var app = new Koa();
var router = new Router();
const serve = require('koa-static');
router
.post([`/getfile/:fileName`],
(ctx) => {
const { params: { fileName } } = ctx;
console.error(`------- server will return ${fileName} --------`);
const readStream = fs.createReadStream(fileName).pipe(ctx.res);
readStream.on('finish', () => {
console.error('---- server finished stream ----');
ctx.status = HttpStatus.OK;
});
})
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3456);
When I change the server to use koa-static, client can gets the file successfully, did diff, look the same.
I suspect server returns too fast before it finishes, but another post said this is the way to wait for pipe to finish.
callback to handle completion of pipe
Any suggestions ? thanks !
ok, I added async, working now
const multiparty = require('multiparty');
const multer = require('koa-multer');
const request = require('request');
var app = new Koa();
var router = new Router();
const serve = require('koa-static');
const streamEnd = fd => new Promise((resolve, reject) => {
fd.on('end', () => {console.error('-- 51 --'); resolve(51); });
fd.on('finish', () => {console.error('-- 53 --'); resolve(53); });
fd.on('error', reject);
});
router
.get([`/getfile/:fileName`],
async (ctx) => {
const { params: { fileName } } = ctx;
console.error(`------- server will return ${fileName} --------`);
if (fs.existsSync(fileName)) {
const readStream = fs.createReadStream(fileName).pipe(ctx.res);
await streamEnd(readStream);
ctx.status = HttpStatus.OK;
} else {
console.error(`File ${fileName} doesnot exist`);
ctx.status = HttpStatus.INTERNAL_SERVER_ERROR;
}
})
app.use(serve('./customer'));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3456);