Unexpected field ERROR in multer file upload - javascript

I'm setting up a server to run my project and using multer on the backend. However, whenever I try to send an image from my frontend to the backend, i get message: "Unexpected field", name: "MulterError", frames.
dependencies that i'm using in my server.js:
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
var singleUpload = upload.single('featuredImage');
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors');
var axios = require("axios");
code in server.js:
app.use(bodyParser.json())
app.use(cookieParser())
app.post('/uploads', singleUpload, function (req, res, next) {
axios.post('http://api.com/api/public/nuxt',
upload,
{
headers:
{
'Content-Type': 'multipart/form-data',
}
})
.then(function(result) {
console.log('SUCCESS!!!!!!!!!!!');
console.log(result.data);
}) .catch(function(){
console.log('FAILURE!!!!1!!!!');
});
return res.json({"status":"success"})
})
module.exports = app

Related

Question about connecting React and NodeJS express

I tried to connect between React(Front End) and NodeJs(BackEnd) and NodeJS -> React(GET) worked well but React -> NodeJS(POST) always erred "POST http://localhost:3001/board/giveresult 500 (Internal Server Error)" and "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" I did all the way to solve that problem but I was stuck at that for a week. what is the problem?
// Method in React
setData() {
let data = {
id:this.state.contents.id, //contents is array in the state
write:this.state.contents.writer,
title:this.state.contents.title,
description:this.state.contents.description
}
fetch('http://localhost:3001/board/giveresult'
,{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(data)
})
.then (res => res.json())
.then (data => console.log(data));
}
//NodeJS Express
const express = require('express');
const app = express();
const receive = require('./routes/receive')
const giveResult = require('./routes/giveResult')
const port = process.env.PORT || 3001;
const cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(bodyParser.json())
app.use('/board/giveresult', giveResult);
app.use('/board/receive', receive);
app.listen(port, function(){
console.log(`connected ${port} port!`);
});
//giveResult
var express = require('express');
const router = express.Router();
var mysql = require('mysql');
const dbconfig = require('../mysql.js');
const { Router } = require('express');
const connection = mysql.createConnection(dbconfig);
var bodyParser = require('body-parser');
router.post('/', function(req, res) {
if(err) throw err;
var post = req.body.id;
console.log(post)
res.send('suceess!!!!');
});
module.exports = router;
Try adding accept in your request header be like .
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}

Error: Request failed with status code 404 (Node.js + Vue.js)?

I am little bit confused and need some help.
I write an HTTP server using Node.js, and make an HTTP request from Vue.js to the HTTP server. Somehow it always return error like this:
Error: Request failed with status code 404
at FtD3.t.exports (createError.js:16)
at t.exports (settle.js:18)
at XMLHttpRequest.f.(:3010/anonymous function) (http://localhost:3010/static/js/vendor.1dc24385e2ad03071ff8.js:1312:88758)
It seems like url address don't correct cause error is 404 in browser. I check url address several times but did't notice something wrong. What I miss?
P.S. The main task to load file from remote sftp server from website. I use to that task ssh2-sftp-client library as backend side.
When user click the button, application run getFile function where we send post request to HTTP server.
Code inside Vue.js component:
getFile (fileName) {
axios.post('http://localhost:3010/csv', {file_name: fileName}, {headers: {'Authorization': this.token}}).then(response => {
console.log(response)
this.showAlert('You download file successfully.', 'is-success', 'is-top')
}).catch((error) => {
console.log(error)
this.showAlert(error, 'is-danger', 'is-bottom')
})
}
app.js:
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const path = require('path');
const bodyParser = require('body-parser');
const csvRouter = require('./server/routes/csv')
const app = express();
app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/csv', csvRouter);
module.exports = app;
routers/csv.js:
const express = require('express')
const router = express.Router()
const csvControllers = require('../controllers/csv')
router.get('/', csvControllers.getFile)
module.exports = router
controllers/csv.js:
const request = require('request')
const queryString = require('query-string')
let Client = require('ssh2-sftp-client')
let sftp = new Client()
const config = require('../config')
exports.getFile = (req, res) => {
console.log(req) // In console I don't notice nothing.
let data = {
file_name: req.query.file_name
}
let options = {
method: 'port',
json: true,
header: {'Authorization': req.header.token},
url: `http://localhost:3010/csv?` + queryString.stringify(data)
}
request(options, (error, response) => {
console.log('Message') // In console I don't notice nothing.
if (response) {
sftp.connect(config.sftpServer).then(() => {
return sftp.get('/reports/' + data.file_name)
}).then((chunk) => {
console.log(chunk)
}).catch((err) => {
console.log(err)
})
} else {
response.status(500).send(error)
}
})
}
It seems that app.listen(port) is missing in your app.js file:
app.listen(3000)
https://expressjs.com/en/starter/hello-world.html
In controllers/csv.js you never send a response. You should have a res.send or res.render or res.json somewhere.

Error setting cookie and getting a json response with router.post in express, node.js

I'm trying to set a cookie with a post method in order to do some db query and put it back in the cookie value, as well as returning a json with the user data.
It works, the cookie is set and I get the json on http://localhost:8080
but I get a message from the compiler:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I fix it so it won’t make this error?
my file structure is:
root/ app.js
root/controllers/ cookie.controller.js
root/routes/ cookie.route.js
app.js
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || process.argv[2] || 8080;
app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());
app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));
cookie.route.js
const express = require('express');
const cookieController = require('../controllers/cookies');
const router = express.Router();
router.use(require('cookie-parser')());
router.post('/', router.use(cookieController.getCookie));
module.exports = router;
cookie.controller.js
exports.getCookie = (req, res, next) => {
let auth = req.cookies.auth;
//...db queries, get userData
let userData = {
id: '123',
token: 'sfsdfs34',
email: 'user#gmail.com'
};
// if cookie doesn't exist, create it
if (!auth) {
res.status(200)
.cookie('auth', userData.id)
.json({ message: 'it works!', user: userData });
req.cookies.auth = userData.id;
}
next();
};
You're modifying the request cookie headers after sending the response at the end of your getCookie controller. You should remove req.cookies.auth = userData.id, and use res.cookie() instead before sending the response.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
app.get('/', (req, res) => {
if (!req.cookies.auth) {
res.cookie('auth', { id: '123' })
}
res.json({ message: 'It worked!' })
})
app.listen(8080, () => console.log('http://localhost:8080))
Problem was solved after deleting the cors from app.js

Express-Fileupload not parsing files in heroku

I am using express-fileupload to parse the body of my request and access any files that are sent with the request. This works fine when I am trying to do this locally but when I push it to heroku, the files are not being parsed - instead req.files is null. My code is below:
Parsing middleware:
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
module.exports = function (app) {
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload()); // EXPRESS-FILEUPLOAD BEING USED HERE
};
Routes file:
router.post('/photo', function(req, res, next) {
console.log("INSIDE OF THE ROUTE =======>>>>>");
const userId = req.body.userId;
const busketName = 'my-bucket-name';
let newPhotosArray = [];
var busboy = new Busboy({ headers: req.headers });
req.pipe(busboy);
busboy.on('finish', function() {
const filesObj = req.files;
console.log('FILES OBJ: ', filesObj); // THIS IS LOGGED OUT AS NULL ON HEROKU - LOCALLY IT IS AN OBJECT WITH FILES
// rest of code....
});
});
The code works great when I use it locally. However, when I push the code to Heroku, req.files is null. Why is this?

Express Post Request 404

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

Categories

Resources