How do I get json data with fetch from my express server? - node.js

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

Related

JSON String not getting to the server (should be easy to solve if you know express js)

I am using express js but for some reason, the server is logging an empty object {} instead of the actual JSON string that I sent. I have worked with so many other technologies like flask, this makes no sense.
Code:
function upload () {
fetch("http://localhost:8080/chat", {
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska#gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
app.post('/chat', function(req, res) {
let test = req.body;
console.log(test);
}
On the "upload" function I do not get the anything logged, and in the server, I get the an empty object {} I mentioned.
If you are to know my issue, I would appreciate help.
Thank you.
UPDATE:
Issue should be in the prontend, as sending the post request with postman works.
I think the error could be happening because you are missing the Content-Type header. You could try this:
function upload () {
fetch("http://localhost:8080/chat", {
headers: {
'Content-Type': 'application/json',
},
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska#gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
You should also make sure that in your server you are using the express.json middleware, this way:
app.use(express.json());

React/Express - Axios get request help needed

Trying to make an API get request from front-end (React) to back-end (Express/MongoDB) using Axios. If I use Postman to make the request it works fine (you can enter a user ID in the request body and get back an array of objects containing that user ID, which is what I want), but doing it from a front-end built in React doesn't work, I just get an empty array returned. As far as I can tell my API call from the front-end is exactly the same as the one I'm making in Postman! Can anyone shed any light on this?
This is the code making the get request from the front end:
const getActivities = async (currentUser) => {
const config = {
crossdomain: true,
headers: {
"Content-Type": "application/json"
},
body: {
"user": `${currentUser[0].id}`,
}
}
try {
const res = await axios.get('http://localhost:5000/api/activities', config)
console.log(res)
dispatch({
type: GET_ACTIVITIES,
payload: res.data
})
} catch (error) {
console.log(error)
}
}
And this is the route on the back-end handling this particular request:
router.get('/', async (req, res) => {
try {
const activities = await Activities.find({ user: req.body.user }).sort({ date: -1 })
if (!activities) {
res.json({msg: "Nothing found. Go forth and exercise!" })
}
res.json(activities).send()
} catch (err) {
res.send(err.message)
}
})
Thanks in advance!
You cannot send a request body with GET method see API AXIOS only for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'.
for example if you want to keep a GET method use params
// React
const config = {
crossdomain: true,
headers: {
"Content-Type": "application/json"
},
params: {
user: `${currentUser[0].id}`,
}
}
try {
const res = await axios.get('http://localhost:5000/api/activities',config)
console.log(res.data)
}catch(err){
...
}
// Express
router.get('/', async (req, res) => {
console.log(req.query.user)
}

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.

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

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

Resources