React - Fetch request not sending content in body - node.js

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())

Related

How do I get json data with fetch from my express server?

I’ve been trying to use fetch to get JSON data from my express server. However, it doesn’t work. I’ve tested the fetch function with JSONPlaceholder so I think my express code is the problem.
Here is my fetch code:
fetch("https://myexpressserver.com/api/example")
.then(response=> {
return response.json()
})
.then(data=> {
console.log(data.text);
})
And here is my express code:
app.get('/api/example', function(req, res){
res.json({ text: 'This is what you should get if this works' });
});
Thank you!
Instead of res.json use res.send!
app.get('/api/example', function(req, res){
res.send({ text: 'This is what you should get if this works' });
});
I also recommend to handle exception and don't use return as it will only cause error in the fetch request:
fetch("https://myexpressserver.com/api/example")
.then(response=> {
response.json();
})
.then(data=> {
console.log(data.text);
})
.catch(err =>{
console.error(err);
})
const RequestOptions = {
method: 'GET',
headers: {'Content-Type': 'application/json' },
};
fetch("https://myexpressserver.com/api/example",RequestOptions).then(Response=> Response.json()).then((data)=>{
console.log(data.txt)
})
try this because RequestOptions is important it tell what type of request we send to server

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);
});
});

Reactjs axios post response is not returning anything

I'm using axios.post() to edit a mysql database on the back end of my Reactjs app. The data gets through the post request to the back end fine. But I need to know when the post request finished and return some data from it to know if what the back end code ran worked correctly. I've tried the following where newEdit is an object with the information that's need in the back end
axios
.post('http://ip:3001/edit_table', newEdit)
.then((response) => {
console.log("response: ",response);
}, (error) =>{
console.log("error: ",error)
});
Neither of the console log statements get ran. Once again, the object does get to the routed nodejs file fine, I am just unable to get any kind of response. Anyone know what's happening? thanks.
if your backend code is OK and return response then you can following below example that works perfectly.
const updateData = async () => {
try {
const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
body: JSON.stringify({
id: id,
title: post.title,
body: post.body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
};
Make sure that your backend is returning a response to the client.
You can either use res.send or res.json. res.send([body]) is used to send HTTP response to the client while res.json(body) is used to send JSON response.
res.send([body])
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
Example:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('hello world')
})
app.listen(3000)
res.json([body])
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
Example:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.json({ success: true })
})
app.listen(3000)
References:
Express API reference
Node.js response object methods res.send and res.json

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);
});
}

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