Blob Objects sent through Axios are empty in Express - node.js

I'm sending a Blob Object created in VueJS to ExpressJS via Axios.post.
But if I send the BlobObject itself via Axiox, I can check it in req.body, but if I send it from ExpressJS to an object that wraps the Blob Object via Axios in order to get it in the form of const {blob} = req.body, ExpresJS BlobObject is empty.
How can I solve this?
Blob Object in Vue Component
Blob {size: 42003, type: ""}
size: 42003
type: ""
__proto__: Blob
Send Blob Object (Axios & Express) 1
// Vue Component
axios.post(`http://localhost:3000/blob`, this.blobObject)
.then(
(response) => {
console.log('Successfully Save API')
},
(err) => {
console.error(err)
}
)
// Express Router
router.post('/blob', (req, res, next) => {
...
console.log(req.body)
})
// req.body
{ "PK\u0003\u0004\n\u0000\u0000\u0000\b\u0000'\u0015\u001aO����%\u0003\u0000\u0000�\u0006\u0000\u0000\f\u0000\u0000\u0000project.json�TA��D\u0014�+�pٕR��3\u001e��\u0001�\u0015\u0005�\u00
16$vEAU%�3ϩ��Ɠ4�\u0012\t!\u000e��\u0004h/{�8U�\u0001�������a�R5T�K���{o�����8iG�:2|pB����\u0011���S\u0018�V6h�ul#f�V��\u0001sO�ǟ�9~�Z": 'x�����l���F�\b6I؏�~�:;\r��l��)\u0019Ї�\u0001���\u001fv�fa��J^��Q�K[��
�v�EM�E��tn�!Q���kܲ����\u0011��q�D\\ӄE�.�"�cʁ�J#g\\���:�쏟~\u000f"�4:���\u0017�a7\u001ba��N�6���f\u001d��IW��\u0010a���\fcN�G?"�(�ˇ\u0003ҙi��CϘ��,�\\\u0015�dE*X\\p�K(ʔ3�^A����:��r��r�zD�a.�(E �l','5\u001c��5�b�5��sC�ۣ���g?�\u001dk�\u0000���`��p�L\f\u0019\n4g�\u0006sle�M$ޚZ�a�\t��<*bZ�k���\u001cM\u0000ԣ��\u001dM{�Ӻ^\u000e��Xʺ�\u0012����\u0017�|q~�|u����_���\u0016��/�"�\u0012V':
'',
....
....
}
Send Blob Object (Axios & Express) 2
// Vue Component
axios.post(`http://localhost:3000/blob`, { "blob": this.blobObject })
.then(
(response) => {
console.log('Successfully Save API')
},
(err) => {
console.error(err)
}
)
// Express Router
router.post('/blob', (req, res, next) => {
...
console.log(req.body)
})
// req.body
"blob": {} // blobObject is Empty

add HTTP headers with Axios request
axios.post(`http://localhost:3000/blob`,
{ "blob": this.blobObject },
{
headers: {'Content-Type':'application/json'}
})
.then(
(response) => {
console.log('Successfully Save API')
},
(err) => {
console.error(err)
}
)
and make sure you have JSON parser middleware eg (if an app is your express app)
app.use(express.json());

Related

Forward file upload data to another API as is with node and express

I have a node endpoint with takes post request for uploading files. I am able to read the data(file) being send from the browser, now I want to forward the data or the whole request to another server hosted somewhere else. I am using node, express and express-fileupload. I am open to get rid on express-fileupload plugin if required.
Following is what I have
app.post("/uploadImage", (req, res) => {
const headers = {
"Content-Type": "multipart/form-data"
};
axios
.post("http://139.59.80.251:8080/homely/images", req.files.file.data, {
headers: headers,
})
.then((resp) => {
res.send(resp);
})
.catch((e) => {
res.status(500).send(e);
});
});
Any help is appreciated.
You must send the buffer data as form-data.
For this, you have to convert the files (buffer data) via the package form-data.
The code should look like this:
const FormData = require("form-data");
app.post("/uploadImage", (req, res) => {
const headers = {
"Content-Type": "multipart/form-data"
};
const my_file = new FormData();
my_file.append("file", req.files.file.data, { filename: req.files.file.name });
axios
.post("http://139.59.80.251:8080/homely/images", my_file, {
headers: headers,
})
.then((resp) => {
res.send(resp);
})
.catch((e) => {
res.status(500).send(e);
});
});

How to make a request and return a response with Express in Node.js?

I trying to send a request to an api and return the response with express when someone curl my site.
app.post('/', async (req, res) => {
request.get('the_api')
.on('response', function(resp){
return res.status(200).send({
text: resp.body
})
})
})
For that requirement, in my projects I use axios, from the documentation:
Axio is a promise based HTTP client for the browser and node.js.
Here is a complete example:
const axios = require('axios');
// api openexchange
const oexchange = axios.create({
baseURL: 'https://openexchangerates.org/api/',
timeout: 60000
})
oexchange.interceptors.request.use((config) => {
config.params = config.params || {};
config.params.app_id = 'myapitoken'
return config;
});
app.get('/', async (req, res) => {
try {
//here it will request:
//https://openexchangerates.org/api/latest.json?app_id=myapitoken
req.oexchange = await oexchange.get('latest.json')
return res.status(200).json(req.oexchange.data)
} catch (e) {
res.status(500).json({ errors: [{ location: 'cotacao', msg: 'Houve um erro ao acessar a api do open exchange.', param: 'openexchangerates' }] })
}
})
In my example I am requesting an external exchange api.
Here is the documentation from axios.
Hope it helps.

POST request with Axios not sending data to my server

Here is my React code for the form submission:
const handleSubmit = (e) => {
e.preventDefault();
console.log('item:', item);
Axios.post('http://<MY_SERVER>/item/add', {name:item})
.then(response => console.log(response))
.catch(err => console.log(err));
};
and this is the code in my Node API:
// Add a new Item
app.post('/item/add', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save()
.then(item => {
res.json({msg: 'success'});
})
.catch(err => console.log(err));
});
When I run the handleSubmit nothing happens. I only get the console.logs... Also, here is the error from my server
'ValidationError: item validation failed: name: Path' `name` is required
So it is clear that the data sent over to the api is never received. I've tried changing it up in many ways I have came across online but no luck.
I have attached both ways to post data i.e. Form URL Encoded and JSON. For sending Form Url Encoded data we need an additional Library querystring.
You can install it using npm install query-string
Here is the code for both the requests. You don't need query-string if you are using content type application/json.
Here you go
var axios = require('axios');
const qs = require('querystring');
function sendFormUrlEncodedData() {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with form url using querystring node package for it.
axios
.post('https://reqres.in/api/users', qs.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
function sendJSONData() {
const headers = {
'Content-Type': 'application/json'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with JSON, so stringifying it.
axios
.post('https://reqres.in/api/users', JSON.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
sendFormUrlEncodedData();
sendJSONData();
First of all check whether your backend code is working or not by using postman. I think you are getting validation error because of the error of your backend code. And also check whether that you are implemented the name attribute correctly with its data type.
After that update, the react code as below.
import axios from 'axios';
constructor() {
this.item = {
name: ''
}
}
handleSubmit(event) {
console.log('item:', this.item.name);
event.preventDefault();
axios.post('http://<MY_SERVER>/item/add', this.item)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}

React - Fetch request not sending content in body

I'm not getting data in body object from fetch request on my server side. I've tried other solutions on SO but nothing is working so far in my case. I'm using Node express on backend and React on frontend.
in component:
addCity = _ => {
const { city } = this.state;
fetch('http://localhost:3003/city_create', {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
create_name: city.name,
create_district: city.district,
create_population: city.population
})
})
.then(res => {
console.log(res);
this.getCities;
})
.catch(err => console.log(err))
}
server route:
router.post('/city_create', (req, res) => {
console.log("Trying to create new city...")
const { create_name, create_district, create_population } = req.body;
//debugger
const queryString = "INSERT INTO city (Name, District, Population, CountryCode) VALUES (?,?,?,'PAK')";
getConnection().query(queryString, [create_name, create_district, create_population], (err, rows, fields) => {
console.log(create_name, create_district, create_population);
if (err) {
console.log('A db error occurred:' + err);
res.sendStatus(500);
return;
//throw err;
}
console.log("Inserted a new City with Id: ", rows.insertId);
});
res.end();
});
tried using FormData and accept property in header as well but no luck.
You need to install body-parser module to extract the entire body portion of an incoming request stream and exposes it on req.body.
It was part of express earlier, now we need to install separately.
npm install body-parser --save
and use the middleware as :
app.use(bodyParser.json())

Indexing user query with Appbaseio and ReactiveSearch

I'm attempting to index a user's query using ReactiveSearch's DataSearch component and appbase-js.
So I've made my Node/Express app for appbase-js interaction with appbaseio.
in app.js:
...
const search = require('./routes/search');
...
app.use('/api/search', search);
Then here is my search.js
const express = require('express');
const Appbase = require('appbase-js');
// create an appbase.io app's instance
const appbaseRef = new Appbase({
url: "https://scalr.api.appbase.io",
app: "index-query",
credentials: "####-####"
});
const router = express.Router();
/* GET search. */
router.get('/test', (req, res, next) => {
res.send('This is the SEARCH route - and it WORKS!');
});
router.post('/query', (req, res, next) => {
appbaseRef.index({
type: "autocomplete",
body: value
}).then('data', response => {
console.log("#index success: ", response);
}),('error', error => {
console.log("#index error: ", error);
});
});
module.exports = router;
Then here is my DataSearch component:
<DataSearch
componentId="SearchSensor"
dataField={["suggestions"]}
className="search-bar"
iconPosition="right"
innerclassName={{
list: "text-item"
}}
onValueSelected{
(value) => {
????
}
}
/>
I was advised in another question not do this:
onValueSelected={(value) => {
fetch('YOUR_SERVER_URL' or 'Elasticsearch URL', { method: 'POST', body: {...} })
}
So as not to expose sensitive information on the client
I'm not sure how to get value (the user's query) from my React front end to my Node/Express backend so that it can be indexed to ES app on Appbaseio?
Say your server is hosted at 'SERVER_URL', the key is to send the data from the frontend to the server via a fetch request:
<DataSearch
...
onValueSelected={(value) => {
fetch('SERVER_URL/api/search/query', {
method: 'POST',
body: JSON.stringify({ value })
}).then(() => handle response client side))
}}
/>
Then you can add the body-parser middleware in express.
app.use(bodyParser.json())
In your route you can use the value from body and index it to elasticsearch. You can use the index method from appbase-js which you're using here.
router.post('/query', (req, res, next) => {
appbaseRef.index({
type: "autocomplete",
body: { value: req.body.value }
}).then('data', response => {
console.log("#index success: ", response);
}),('error', error => {
console.log("#index error: ", error);
});
});

Resources