Axios GET request fails to hit endpoint without params object - reactjs

I am making a request to a custom endpoint...
VideoAPI.get('/api/getVideo/:id', function(req, res){
console.log('FROM URL STRING', req.params)
console.log('FROM PARAMS OBJECT', req.query)
res.end()
}
If if make an Axios post like so, it never hits the endpoint and I get a 300 status response client side:
axios.get(`/api/getVideo/2`)
.then( res => {
console.log(res)
})
But if I make the call like so, it hits the endpoint as expected, even if the params object is completely irrelevant data:
axios.get(`/api/getVideo/2`, {
params : {
bogus: 'WTF'
}
})
.then( res => {
console.log(res)
})
My console will read:
FROM URL STRING { id: '2' }
FROM PARAMS OBJECT { bogus: 'WTF' }
What am I not understanding here?

Related

Axios: Pass data in GET method

I have created a config file to create an Axios.
export const http = axios.create({
baseURL: process.env.REACT_APP_API_URI,
responseType: "json",
timeout: 30000,
timeoutErrorMessage: "Request Time out",
headers: {
withCredentials:true
}
})
In the other file, I have created helper functions to post, update, and get. Now I am trying to pass data from the body through the get function so far I have following code to get data without passing the body.
export const getRequest = (url, is_strict = false) => {
return new Promise((resolve, reject) => {
http.get(url, {
headers: getHeaders(is_strict)
}).then((response) => {
if(response.status === StatusCodes.OK || response.status === StatusCodes.CREATED){
resolve(response.data);
} else {
reject(response);
}
})
.catch((error) => {
reject(error);
})
})
}
How can I achieve that?
You cannot have a request body in GET method. You can use request params instead. Or you can use POST method.
Form the MDN docs for GET,
property
avaiability
Request has body
No
Request has body
Yes

Send data react axios

Send data React to Node
If send data with axios.
is it correct?
react:
let data = {pp: number};
axios.post('http://localhost:3001/number', {
body: data
}). then((response) => {
console.log('data submitted success');
}).catch((error) => {
console.log('got err', error);
});
this in server
router.post('/', function (req, res) {
var countValue = req.body;
console.log('CountValue is', countValue);
});
It seems you need to put bodyParser.json() in your middleware.
For example:
app.use(bodyParser.json());
After that, you could use below code as your HTTP response in the controller.
res.status(200).json({ results: countValue });
I believe you don't need to use JSON.stringify(countValue)
Feel free to share more details for us :)

Send multi request by axios, stop all request if first response 500 and redirect to login

I'm using axios 0.19.2, I send some requests to backend like this:
axios.get(API_PATH+'/request_a').then(res => res.data)
axios.get(API_PATH+'/request_b').then(res => res.data)
axios.get(API_PATH+'/request_c').then(res => res.data)
axios.get(API_PATH+'/request_d').then(res => res.data)
I try to make backend return 500 error code in the first request and I want to stop after requests.
window.axios = axios.create({
validateStatus: (status) => {
// console.log(status);
return true;
}
});
window.axios.interceptors.response.use(function (response) {
// console.log(response.data);
return response;
}, error => {
console.log(error);
return Promise.reject(error);
});
I try to redirect with window.location in validateStatus, window.axios.interceptors.response.use where I can get response but browser spin unlimitted due to to many request are sent in the same time. How do I fix this?

Body of request received on Express backend is different than how i sent it from React frontend

I am trying to send a post request from my React front end to my Express front end, for some reason, the object I want to recieve, is being displayed so that the object is the key of another object and the value is and empty string.
Here is my onSubmit React function
handleSubmit = event => {
event.preventDefault()
const backend = '/api/login'
fetch(backend, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: JSON.stringify(this.state)
})
.then(res => {
res.json()
})
.then(user => {
console.log(user)
})
.catch(err => {
console.log(err)
})
}`
And my post function on the express server
app.post("/login", (req, res) => {
console.log(req.body)
})
For example, if the object I want to send is {username: "user1", password: "password"}, when I console.log(req.body), I get { '{"username":"user1","password":"password"}': '' } in the console.
How do i fix this so i get the object that I requested?
Because it is JSON format. To parse it you can use:
JSON.parse('{"username":"user1","password":"password"}')
or JSON.parse(req.body)
The approach is fine with JSON.stringify() because it should be posted just like a string to the server. But if you want it to be an object at the backend then you have to parse it back with:
const userObj = JSON.parse(req.body.Data); // it will parse it back as an object

Send parameter not in URL to API

I send a request to my API with advancedFetch. This works, however, I want to know if it is possible to send a parameter without defining it in the URL. Are there any smart ways of doing this?
I tried researching it but I'm not sure I'm using the right keywords for what I'm trying to do.
This is where I set off my request (the value is from a modal input field):
setNewUserName(userName) {
this.setState({newUserName: userName});
advancedFetch('/api/users', {
method: 'POST',
body: JSON.stringify({}),
credentials: 'include',
// I've tried sending the param here
userName: userName,
headers: {
'Content-Type': 'application/json'
}
})
.then(() => {
this.loadUsers();
})
.catch(err => {
//error handling
});
}
In my controller I defined the route and implemented function like this:
index.create = (req, res, next) => {
let userName = req.params.userName;
console.log(userName);
user
.create(userName)
.then((response) => {
res.send(response);
})
.catch((err) => {
next(err);
});
};
router.post('/users', index.create);
And then in my service.js I write the data to my database:
create: function(userName){
userName = userName
return query(`INSERT INTO ${tableName} (user) VALUES (?, ?)`, [1, userName])
.catch(err => {
app.logger.error('[Users] failed to create a user', err.message);
return Promise.reject(new Error('failed to create user'));
});
},
I always get an undefined userName, do I have to create a route with the value at the end?
You're receiving userName as undefined, because you're sending the request with JSON-encoded data, rather than URL parameters and the same logic doesn't apply for that case.
Luckily there's an easy way to solve your problem, using expressjs body-parser package. It's very easy to use.
This is how you initialize it:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
And this is how you would read "userName" in your router function:
index.create = (req, res, next) => {
let userName = req.body.userName;
console.log(userName);
user
.create(userName)
.then((response) => {
res.send(response);
})
.catch((err) => {
next(err);
});
};
And btw, when you're calling advancedFetch, you should actually be doing this:
body: JSON.stringify({newUserName: userName}),
Yes, you can actually do it this way:
In the frontend call you can send the parameter through the body like so
body: JSON.stringify({userName: userName})
And then in your controller what you want to do is to directly access the paramter from the body:
let userName = req.body.userName;
And now it's not undefined anymore :)

Resources