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

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

Related

axios get res.data = null

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

Passing parameters using React fetch to access Node API

I have a react project with NODE API backend. I am facing issues with the very basic fetch GET request. When passing parameters through link, it cannot be accessed at the server side.
My react function:
const loadOptions = async (cnt) => {
const response = await fetch(`${baseurl}/pdt/prev=${prev}&cnt=${cnt}`);
const resJSON = await response.json();
};
NodeJS express router code:
router.get("/pdt/:prev/:cnt", async (req, res) => {
try {
console.log(req.params.cnt);
console.log(req.params.prev);
} catch (err) {
res.json(err.message);
}
});
The result is :
Edited React code based on the answers I got above. Thank you #Phil
const response = await fetch(`${baseurl}/pdt/${prev}/${cnt}`);
It's working now.
another solution from backend
router.get("/pdt", async (req, res) => {
try {
console.log(req.query.prev);
console.log(req.query.cnt);
} catch (err) {
res.json(err.message);
}
});
and modify request
fetch(`${baseurl}/pdt?prev=${prev}&cnt=${cnt}`)

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.

Unable to post data or send a file using axios and form-data

I am trying to post data from my nodejs app to a an endpoint.
I tested sending some data to that endpoint using Postman and all works fine, I got the posted data and all got printed to the console.
but I am always getting empty post data at my endpoint when sending from my nodejs using axios.
here is my code:
const FormData = require('form-data');
const axios = require('axios');
function send_to_test() {
const endpoint = 'http://localhost:5000/test';
const form = new FormData();
form.append('string_var', 'some string');
form.append('integer_var', 100);
axios.post(endpoint, form, { headers: form.getHeaders() }).then((res) => {
console.log(res.data);
});
};
and here is my endpoint (I am using express js server):
app.post('/test', function(req, res) {
console.log(req.body);
res.json({
status: 'success'
});
});
Unable to get this working, please advise and thanks in advance.
You need to setup a form parser at the your endpoint. You can make use of formidable. code for reference:
const form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if (err) {
return res.status(400).json({ error: err.message });
}
res.json({
status: 'success'
});
}
I hope it gives you better picture!

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