axios get res.data = null - node.js

I've had a blockage since last night and I still don't understand, let me explain.
I use React, Mongo DB, and NodeJs, and axios for my API calls
I created a route to retrieve the info of a user, when I test the route with PostMan, I have the user info so everything works as it should, only when I make the api call from my front, my res.data returns "null", so I think it's coming from my api call, but I can't find what's wrong.
I am attaching some screenshot, thank you in advance:
API call :
function Post() {
axios({
method: "get", url: "http://localhost:4000/api/auth", credentials: true,
params: {
userId: "62f045f5253a960077a8ff3f"
}
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}
Function back getOneUser:
exports.getOneUser = (req, res, next) => {
userModel.findOne({_id: req.params.userId}).select('-password -email')
.then(post => res.status(200).json(post))
.catch(error => res.status(404).json({error}))
}

In express, use req.query instead of req.params.
This post might clarify the differences between them

Related

Node fetchi request using axios returns gibberish data as response

I am a beginner in node and I am trying to consume an API,but response returns gibberish data.I have tested the API routes and I am sure the problem is my request but I clearly cannot tell where.I think I am making an obvious mistake but it is hard to tell.
Here is the function to generate the token
const generateToken = async (req, res, next) => {
const secret = proces.env.MPESA_CONSUMER_SECRET;
const consumer = process.env.MPESA_CONSUMER_KEY;
const auth = new Buffer.from(`${consumer}:${secret}`).toString("base64");
await axios
.get(
"https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials",
{
headers: {
authorization: `Basic ${auth}`,
},
}
)
.then((response) => {
console.log(response);
// token = response.data.access_token;
next();
})
.catch((err) => {
console.log(err);
//res.status(400).json(err.message)
});
};
app.get("/token", (req, res) => {
generateToken();
});
the response I get after console.log is this
data: '\x1F�\b\x00\x00\x00\x00\x00\x00���R#\x02J��ɩ���%�٩yJV\n' +
'J��.�EU�\x1E��Y�N)%IQ\x01\x05\x16���&N�f\x01J:�zS+\n' +
'2�R��3�:�M--��\n' +
'j�,\x00�H��q\x00\x00\x00'
}
Anyhelp to even help me understand where the problem could be will be highly apprecited.
In v1.2.1 fixed this error.
Try it after install axios(v1.2.1) again
Downgrading to Axios version 1.1.3 worked for me
If you are using an older version of axios v1.2.1 should fix the issue

I cant get a response from a POST request with an array in the body, Using NodeJS / Axios and Postman

This is a course quiz and this is the most basic information I need in order to create a React app. But while the endpoint URL is correct, the page "/products" returns a "400" error when I try to request the product list. The instructions I'm given are:
Obtain a list of products with
Route: /products
Body: Array
method: POST
{
"product-codes": [
"98798729",
"84876871",
"29879879",
]
}
My index.js
...
app.post(`/products`, async (req, res) => {
try {
const response = await axios.post(`${apiURL}/products`);
// console.log(response.data);
res.status(200).json(response.data);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
in Postman
I use http://localhost:4000/products
and pass a Body / Raw /JSON:
{
"product-codes": [
"98798729",
"84876871",
"29879879",
]
}
But I can't get in! I am not seeing something obvious because this is the entry point to a very long and complex quiz. Thanks
What I see from the code is a recursive long call.
app.post(`/products`, async (req, res) => {
try {
const response = await axios.post(`${apiURL}/products`); // calling the same end point
// console.log(response.data);
res.status(200).json(response.data);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
You should do something like this:
app.post(`/products`, async (req, res) => {
// do your logic
// when you pass body from postman on this endpoint
// you will receive the body here and save it to DB
// or do the manipulation and then send back the response
res.status(200).json(req.body.data);
});
I highly recommend you to first follow through some tutorials to understand how API works and how to create simple API using Node.js.

Using Node and Express, How to Call remote API from inside server.get(..)

Because of CORS problems, I want to call an external REST API from inside my node express server. That is, I have code like this that obviously does not work because it does not return.
How can I make this work and return the results of my external call?
const server = express();
server.put('/callme',(req,res) => {
axios
('http://weather.com/restapi', 'put', { zip: 10530 })
.then((resp: any) => {
console.log(' success' + resp.data);
})
.catch(function(error: any) {
console.log(error.message);
});
}
Axios returns a Promise which is resolved in the .then(). In order to get the response data back to the client you need to return it with res.send().
const server = express();
server.get('/callme', (req, res) => {
axios
.get('http://weather.com/restapi?zip=10530')
.then((resp: any) => {
res.send(resp.data);
})
.catch(function(error: any) {
console.log(error.message);
});
}
It would be a good idea to cache the weather API response for a period of time and serve the cached response for subsequent requests.

can't pass data in to delete request with Vue-Resource

im getting problem with passing data in to delete request with Vue-resource. Server is reciving blank object without data. There is some code:
Front-end with Vue.js and Vue-resourcer
deleteArticle: function(tit){
console.log(tit);
this.$http.delete('http://192.168.0.52:8080/article',{'title':'123'}).then((res)=>{
this.refresh();
console.log(res.data);
}).catch((e)=>{console.log(e)});
}
Back-end with node.js route using express.js API.
app.delete('/article', (req,res)=>{
var body = _.pick(req.body,['title']);
console.log(req.body); //printing blank object from request
Article.findByTitleAndRemove(body.title).then((doc)=>{
res.status(200).send(`Deleted Article with title ${doc.title}`)
}).catch((e)=>{
console.log(e);
res.status(400).send(e);
})
})
This route works with postman.
Try this:
this.$http.delete('http://192.168.0.52:8080/article', { params: { title: 123 } }).then(res => {
this.refresh();
console.log(res.data);
}).catch((e)=>{console.log(e)});
Update: this is how this works for me in node:
app.delete('/article', (req, res) => {
console.log(req.query.title);
});

Sending data to express backend

I am learning how to use express, and I am able to get data, but I'm having more trouble figuring out how to send data back to update the backend. Here is an example of what it looks like.
server.js
app.route('/animals')
.get(function (req, res) {
res.send({ Cat, Dog, Bear, Wolf, etc... });
})
.patch(function (req, res) {
console.log('patch is working!')
// unsure of how to get this called with react or use req here
})
react front end
componentDidMount(){
this.callApi()
.then(res => this.setState({ name: res[this.state.animal].name }) )
.catch(err => console.log(err))
}
callApi = async () => {
const response = await fetch('/animals');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
This works flawlessly when getting the data, so i have .get down, but I am running into walls trying to use .patch. I can't get the console.log to fire,
let alone send it data! (lets say instead of trying to get the animal name, I'm trying to update it's name.) Any ideas? Thanks ahead of time.
The fix in this case was adding JSON.stringify in addition to what RishikeshDhokare shared! I hope this can help someone else down the line.
const response = await fetch('/animals', {
method: 'PATCH',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({ name: 'kitten})
});

Resources