I have an angular application and express server a middle ware which call the external API
$scope.uploadLayout = function(){
$scope.selectedTemplate.selected = $scope.items;
var fd = new FormData()
fd.append('name', $scope.template.name)
fd.append('description', $scope.template.desc)
fd.append('file', $scope.template.file)
$http.post('/layout/template',fd,{
transformRequest: angular.identity,
headers: { 'Content-Type': undefined}
}).then(function(response){
getLayoutRules()
console.log("file uploaded successfully")
})//add error callback
console.log('test')
}
The main problem occurs when express sends the data to the external API
app.post('/layout/template', upload.any(), (req, res) => {
// console.log(req.body.name);
var formdata = new Buffer(req.files)
var form = new FormData();
form.append('name', req.body.name)
form.append('description', req.body.description)
form.append('file', formdata)
console.log(form)
var contentLength = req.files.length;
var url = `${apiUrl}/layout/template`
// var r = request.post(url,{
// headers: { 'Content-Type': undefined}
// }, function optionalCallback(err, httpResponse, body) {
// if (err) {
// return console.error('upload failed:', err);
// }
// console.log('Upload successful! Server responded with:', body);
// })
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'multipart/form-data'
},
url:url,
method:'POST',
body: form
},function(err,body,res){
console.log(err)
console.log(body)
})
});
I have checked the form is generating properly but the external API server gives me an error saying that
"The request was rejected because no multipart boundary was found"
Kindly help, or is there any other way round it
UPDATE
I modified the code a bit to send the request headers fetched from the browser
app.post('/layout/template', upload.any(), (req, res) => {
var header = req.headers['content-type']
var formdata = new Buffer(req.files)
console.log(formdata)
var fd = new FormData();
fd.append('name', req.body.name)
fd.append('description', req.body.description)
fd.append('file', formdata)
//var contentLength = req.files.length;
//console.log(contentLength)
var url = `${apiUrl}/layout/template`
//console.log(fd)
// var r = request.post(url,{
// headers: { 'Content-Type': undefined}
// }, function optionalCallback(err, httpResponse, body) {
// if (err) {
// return console.error('upload failed:', err);
// }
// console.log('Upload successful! Server responded with:', body);
// })
request({
headers: {
'Content-Type': header
},
url:url,
method:'POST',
body: fd
},function(err,body,res){
//console.log(body)
console.log(res)
})
//console.log(request)
});
So now i am sending the same boundary set by browser but now the form parameters are not detected by java server
Related
I am trying to make a server for a website. The server works perfectly, and it can receive and send data normally. I have hosted the server, and I made a demo client-side repl on Replit to test the flow. But somehow, either the reply isn't receiving or sending properly, or the server isn't working. (For the client-side code, I am using JQuery)
// Client Side Code
const url = "My url";
const data = {
"file": "lol.html"
}
function start() {
console.log("test 1")
$.post(url, data, function(data, status) {
console.log(data + "is data & status is " + status);
});
}
// Server-side code
var http = require('http'); // Import Node.js core module
var fs = require('fs'); // File System
var url = require('url');
var server = http.createServer(function(req, res) { //create web server
if (req.url == '/') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "This is the Backend server for my website" }));
res.end();
}
else if (req.url == "/ping") {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Pong!" }));
res.end();
}
else if (req.url.startsWith("/read")) {
var q = url.parse(req.url, true);
var qdata = q.query;
fs.readFile(String(qdata.file), function(err, data) {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}
else if (req.url.startsWith("/get")) {
var q = url.parse(req.url, true);
var qdata = q.query;
fs.readFile(String(qdata.file), function(err, data) {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}
else {
res.end('Invalid Request!');
}
});
server.listen(5000); //6 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
Can Someone tell me how to perform this properly?
I'm trying to send a file "image" with another post parameters using axios with react library, this is my original code which works very well sending one image or a file to the server.. in the server i'm using multer library to save the images:
submitFormImagen(e){
e.preventDefault();
const token = localStorage.getItem('auth-token');
const formData = new FormData();
formData.append('myImage',this.state.file);
const config = {
headers: {
'content-type': 'multipart/form-data',
'auth-token': token
}
};
axios.post("http://localhost:5000/api/user/upload",formData,config)
.then((response) => {
alert("The file is successfully uploaded");
console.log(response)
this.setState({imagen: response.data.imagen})
}).catch((error) => {
});
}
in this case: formData is necessary to multer library can save the image; this is my code from the server:
router.post('/upload', verificarToken, async function(req,res){
//imagen nombre: req.file.filename
console.log(req.body)
const url = req.protocol + '://' + req.get('host')
const _id = req.user._id
upload (req, res, async function(err) {
if(err) {
return res.end("Ocurrio un error al subir el archivo.");
}
const rutaimagen = url + "/uploads/" +req.file.filename
//Actualizar Imagen del usuario:
await User.findByIdAndUpdate(_id, {
imagen: rutaimagen
});
//res.end("Archivo subido correctamente!");
res.json({imagen: rutaimagen})
});
});
basically that's it now i'm trying to capture the request body to try to update the user image and his name and email..
this update does not work:
submitFormImagen(e){
e.preventDefault();
const token = localStorage.getItem('auth-token');
const formData = new FormData();
formData.append('myImage',this.state.file);
var post = {
myImage: this.state.file,
name: this.state.name,
email: this.state.email
}
const config = {
headers: {
'content-type': 'multipart/form-data',
'auth-token': token
}
};
axios.post("http://localhost:5000/api/user/upload",post,config)
.then((response) => {
alert("The file is successfully uploaded");
console.log(response)
this.setState({imagen: response.data.imagen})
}).catch((error) => {
});
}
Also I tryed:
formData.append('myImage',this.state.file);
var post = {
name: this.state.name,
email: this.state.email
}
formData.append('anotherdata',post);
const config = {
headers: {
'content-type': 'multipart/form-data',
'auth-token': token
}
};
axios.post("http://localhost:5000/api/user/upload",formData,config)
...
and now i'm trying to get the value of "anotherdata" inside the upload function from the server which is inside the upload route.. but I got:
[Object: null prototype] { anotherdata: '[object Object]' }
this is the code of the server:
router.post('/upload', verificarToken, async function(req,res){
//imagen nombre: req.file.filename
const url = req.protocol + '://' + req.get('host')
const _id = req.user._id
upload (req, res, async function(err) {
console.log(req.body) //<*********
if(err) {
return res.end("Ocurrio un error al subir el archivo.");
}
Vaguely following this 'tutorial': https://stackabuse.com/the-node-js-request-module/
I get to the alert ('Options Declared'), but then my program stops at the request and I have no idea why.
const request = require('request');
function testGet(){
alert("Get test started");
const options = {
url: "https://www.reddit.com/r/funny.json",
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
}
alert("Options declared");
request(options, function(err, res, body){
let json = JSON.parse(body);
console.log(json);
});
alert("Get test done");
}
Just send the response and error as the response object and look at what comes.
const request = require('request');
function testGet(){
alert("Get test started");
const options = {
url: "https://www.reddit.com/r/funny.json",
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
}
alert("Options declared");
request(options, function(err, res, body){
res.json({err : err, result: body});
});
}
You place the request function declaration and body inside testGet().
Please do that outside the testGet() like this.
function testGet(){
alert("Get test started");
const options = {
url: "https://www.reddit.com/r/funny.json",
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
}
alert("Options declared");
request.post(options, callback);
}
request(options, function(err, res, body) {
let json = JSON.parse(body);
console.log(json);
alert("Get test done");
});
I am trying to request data from RESTful API and sharing the result to html web page using Node.js. My code runs well, but I want to make this RESTful request every time I call the webpage not just when I run a Node.js server.
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var request = require("request");
var temp = "";
var options = { method: 'GET',
url: 'My_URL',
headers: { authorization: 'Basic My_Autho' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
temp = body;
console.log(body);
});
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'
});
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var renderedHtml = ejs.render(content, {temp: temp});
res.end(renderedHtml);
});
}).listen(8000);
Maybe you could move your call to the external REST api inside the request handler ?
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var request = require("request");
var temp = "";
var options = { method: 'GET',
url: 'My_URL',
headers: { authorization: 'Basic My_Autho' }
};
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
request(options, function (error, response, body) {
if (error) throw new Error(error);
temp = body;
console.log(body);
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var renderedHtml = ejs.render(content, {temp: temp});
res.end(renderedHtml);
});
});
}).listen(8000);
Trying to upload pdf file on node js server using fetch() on client and express + multer on server, query status 200, but there is emty object in req.body and empty req.file. Pls check my code below on client.
client.js
fetch(path, conf) {
let myConf = config;
return fetch(myConf.apiUrl + path, conf)
.catch(err => {
console.warn('api error: ' + err.message)
})
},
sendForm(data) {
if (!data) {
return
}
let header, body;
const fd = new FormData();
fd.append('file', data.file.files[0])
header = 'application/pdf';
body = fd;
return this
.fetch('/connect', {
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': header
},
body: body
})
.then(res => {
if (!res.ok) throw new Error('error ' + res.status)
return res
})
}
And server side:
server.js
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: './uploads/' });
const app = express();
app.post('/connect', upload.single('resume'), function(req, res, next) {
res.send({
body: req.body,
file: req.file,
files: req.files
})
});
Result in Postman: http://prnt.sc/e1ib8o