Why axios does not send request with params? - node.js

function googleFind(what,where){
var links = []
axios
axios.get(`https://www.google.com/`,{params: {
"search?q=": what,
}})
.then(res => {
fs.writeFileSync("text.html",res.data)
})
.catch(err => console.log(err))
}
googleFind("Something","znanija.org")
The code must send get request:"https://www.google.com/search?q=Something",
but it just ignored "params",
help pls

Search should be part of the URL and params should be passed as an object.
axios.get('https://www.google.com/search', {
params: {
q: what,
},
});

Related

An problem occur when submit a GET Request by node-fetch

I am using node-fetch to fetch data from REST API.
Here is my code:
this.getUserList = async (req, res) => {
const fetch = require('node-fetch');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
let params = {
"list_info": {
"row_count": 100
}
}
fetch('https://server/api/v3/users?input_data=' + JSON.stringify(params), {
headers:{
"TECHNICIAN_KEY": "sdfdsfsdfsd4343323242324",
'Content-Type': 'application/json',
},
"method":"GET"
})
.then(res => res.json())
.then(json => res.send(json))
.catch(err => console.log(err));
}
It works fine.
However, if I change the following statement:
let params = {"list_info":{"row_count": 100}}
To
let params = {"list_info":{"row_count": 100}, "fields_required": ["id"]}
It prompts the following error message:
FetchError: invalid json response body at https://server/api/v3/users?input_data=%7B%22list_info%22:%7B%22row_count%22:100%7D,%22fields_required%22:[%22id%22]%7D reason: Unexpected end of JSON input`
The problem is that you are not URL-encoding your query string. This can be easily accomplished using URLSearchParams.
Also, GET requests do not have any request body so do not need a content-type header. GET is also the default method for fetch()
const params = new URLSearchParams({
input_data: JSON.stringify({
list_info: {
row_count: 100
},
fields_required: ["id"]
})
})
try {
// 👇 note the ` quotes
const response = await fetch(`https://server/api/v3/users?${params}`, {
headers: {
TECHNICIAN_KEY: "sdfdsfsdfsd4343323242324",
}
})
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
res.json(await response.json())
} catch (err) {
console.error(err)
res.status(500).send(err)
}

Axios is returning undefined

My API is returning proper data when I am requesting from Postman. Even API is getting properly called from React, I checked using console.log inside the controller, but I am always getting undefined response. I am not sure what the mistake is.
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
const response = await axios
.get('certificates', {
params: { sponser },
})
.then((res) => {
console.log(response); //undefined
alert(res.status); //200
alert(res); //[object Object]
});
};
Could you please help me on the same.
You need to return res in the then to have access on response:
const response = await axios
.get('certificates', {
params: { sponser },
})
.then((res) => {
console.log(response); //undefined
alert(res.status); //200
alert(res); //[object Object]
// response is not defined here!
return res;
});
console.log(response);
Shorter way:
const response = await axios
.get('certificates', {
params: { sponser }
});
console.log(response);
It seems that OP is relatively new to js - I can recommend this intro to async js: https://javascript.info/async-await

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 send React to Express server get Request passing id

Hello I am learning on MERN Stack dev, so I am trying to implement a get request where by I send in and ID and then try searching through the collection by the id the return the entry back to the client so I have been trying to implement this but I do not know where I am going wrong because I get a 404 response
Code below is the client side where I try to send through the get request
const ProductDetails = (props) => {
const product_id = window.location.href.split("/")[4];
console.log(product_id);
const getProduct = () => {
const url = `http://127.0.0.1:5000/single-women-clothes/id?=${product_id}`;
Axios.get(url)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
};
getProduct();
return (
<div>
<h1>Details</h1>
</div>
);
};
router.get("/single-womens-clothes/:id", (request, response) => {
console.log(request.params);
MongoClient.connect(
mongoURI,
{ useNewUrlParser: true, useUnifiedTopology: true },
(error, client) => {
client
.db("OnlineStore")
.collection("WomensClothes")
.find(request.params.id)
.toArray()
.then((data) => {
response.status(200).json(data);
})
.then((response) => {
console.log("Single Female Product Fetch Successful");
})
.catch((error) => {
console.log(error);
});
}
);
});
Can I please get help on how I can pass the ID to the server then search through collection through this given ID
Anytime you have a 404 error, the issue is usually coming from putting the wrong url.
In your front-end:
single-women-clothes/id?=${product_id}
Backend
/single-womens-clothes/:id
You are missing an "s" in the front-end url in "womens"
To answer your second question:
You shouldn't do id?= just simply leave it as
single-women-clothes/${product_id}

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

Resources