Axios is returning undefined - node.js

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

Related

Axios - API returning HTML instead of JSON

I'm developing an application using the MERN stack. As I deployed my demo version on render.com, I faced some issues. Sometimes the Axios request is returning HTML, instead of a JSON file.
ItemController.js
const getItem = async (req, res) => {
const { type } = req.params;
if (!type) {
throw new BadRequestError("Please provide all values");
}
const items = await Item.find({ type: type });
res.status(StatusCodes.OK).json({ items });
};
Request
const authFetch = axios.create({
baseURL: "/api/v1",
});
//Request
const findItems = async () => {
dispatch({ type: LOADING_ITEMS_BEGIN });
let url = "/items";
if (state.currentCategory) {
url = url + "/" + state.currentCategory;
}
try {
const { data } = await authFetch.get(url);
console.log(data);
dispatch({ type: LOADING_ITEMS_SUCCESS, payload: { data } });
} catch (error) {
console.log(error);
dispatch({
type: LOGIN_USER_ERROR,
});
}
};
I've checked the request URL, it's always fine. But it seems like the requests do not even reach the server when it sends back HTML, and I get 200 as a status code.
I tried to trace the request, but couldn't find any clue
Edit: It seems fine using Postman, so something is definitely wrong with the request.

Why axios does not send request with params?

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

getting error 400 with axios post request & undefined error

I'm making a project to store the data in mysql using react-native. and node.js server
but i faced two problems One is TypeError in object : undefined and the other is getting error 400 with axios post request. I trying to another way for solve second problem (chage the param to formData - but this is doesn't work error 404) Sorry if this is a stupid mistake, as i am new to working with react native and node.js.
React native code
onPress={() => {
AsyncStorage.getItem("pubKey").then(pubKey => {
AsyncStorage.getItem("name").then(name => {
const {
data: { article }
} = axios.post("http://127.0.0.1:4000/apply",null,{
params: {
articleId: id,
apubKey: pubKey,
name: name,
},
headers: {'Content-Type' : 'application/json'},
});
alert('지원 확인')
console.log(article)
})
})
}}
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_axios$post.data.article')]
[Unhandled promise rejection: Error: Request failed with status code 400]
node.js (apply.js)
router.post("/", function (req, res) {
console.log("req.body.params: ",req.body)
console.log("req: ",req)
Article.findAll({
attributes: ["id", "db_pubKey", "db_title", "db_wtype"],
where: {
id: req.body.articleId
}
})
.then(result => {
console.log("result : " + JSON.stringify(result));
let DB2 = JSON.stringify(result);
let DB1 = JSON.parse(DB2);
let DB = DB1[0];
if (DB) {
console.log("DB", DB);
Apply.create({
db_apubKey: req.body.params.apubKey,
db_articleId: req.body.params.articleId,
db_opubKey: DB.db_pubKey,
db_title: DB.db_title,
db_wtype: DB.db_wtype,
db_name: req.body.params.name,
db_accept: null
})
.then(result => {
console.log("result : " + result);
res.status(201).json({ result: 1 });
})
.catch(err => {
console.error("err : " + err);
});
} else {
res.json({ result: 0 });
}
})
.catch(err => {
console.error("err : " + err);
next(err);
});
});
All API calls are asynchronous, so you need to handle an asynchronous action with proper strategies like async/await or then/catch method.
With the async/await method:
onPress={async () => {
try {
const pubKey = await AsyncStorage.getItem("pubKey")
const name = await AsyncStorage.getItem("name")
const result = await axios.post("http://127.0.0.1:4000/apply", null, {
params: {
articleId: id,
apubkey: pubKey,
name: name,
},
headers: {'Content-Type' : 'application/json'},
})
const article = await result?.data?.article
alert('지원 확인')
console.log(article)
} catch (error) {
// do proper action on error/failure cases
console.log(error)
}
}}
Note: don't forget to use catch method for your API calls.
Note: as a side note, you can't call an http URL in production application, it must be an https
Note: you might need to specify the article type and pass it.
About the 400 error on your backend side:
change this line router.post("/", function (req, res) { to :
router.post("/apply", function (req, res) {
// rest of the codes ...
You've forgotten to add your API name correctly.

Server not sending correct response to frontend?

I am trying to make my server a middleman so that the frontend queries the server with a searchedValue, the server queries the API with the searchedValue, and the server returns the API response to the frontend.
Currently, the server is querying the API correctly. Here is the code and responses:
Query: http://localhost:3000/optionsAPI/AAPL
Code [server.js]:
app.get("/optionsAPI/:ticker", (req, res) => {
var tempJSON = [];
const searchString = `${req.params.ticker}`;
const url = `API URL HERE, HIDING FOR SECURITY`;
fetch(url, { headers: { Accept: 'application/json' } })
.then(res => res.json()
.then((json) => {
tempJSON = json;
console.log(tempJSON);
}))
.catch(err => console.error(err)); // eslint-disable-line
res.send({ message: tempJSON });
});
Here is the code in the component:
Code [Component.js]:
useEffect(() => {
const fetchData = () => {
const url = `/optionsAPI/${searchedValue}`;
fetch(url, { headers: { Accept: 'application/json' } })
.then(res => res.json()
.then((json) => {
setOptions(json.option_activity || []);
}))
.catch(err => console.error(err)); // eslint-disable-line
};
debounce(fetchData());
}, [searchedValue]);
The console log is perfect! It logs tempJSON as I would expect to see it, but the res.send message is simply {"message":[]}. Therefore, the response my frontend gets is an empty []. This doesn't; make sense - the console is logging the response, so why is the frontend receiving a blank []?
Thanks in advance.
In your code you are calling an api which returns a promise, so to handle the data returned by the promise you should add your code inside .then() function, meaning you have to wait for the promise to be resolved before accessing the data and sending it to the client
app.get("/optionsAPI/:ticker", (req, res) => {
var tempJSON = [];
const searchString = `${req.params.ticker}`;
const url = `API URL HERE, HIDING FOR SECURITY`;
fetch(url, { headers: { Accept: 'application/json' } })
.then(res => res.json()
.then((json) => {
tempJSON = json;
console.log(tempJSON);
// the response should be sent from here
res.send({ message: tempJSON });
}))
.catch(err => {
console.error(err);
// you also need to send a response when catching erros
res.status(400).send({ err });
});
});
you can use async / await to make your code much cleaner
app.get("/optionsAPI/:ticker", async (req, res) => {
var tempJSON = [];
const searchString = `${req.params.ticker}`;
const url = `API URL HERE, HIDING FOR SECURITY`;
try {
const result = await fetch(url, { headers: { Accept: 'application/json' } })
const json = await result.json()
tempJSON = json;
console.log(tempJSON);
res.send({ message: tempJSON });
} catch (error) {
console.error(error);
res.status(400).send({ error });
}
});

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