Passing parameter to a GET request to retrieve specific information - javascript

I am trying to retrieve (GET) specific information based on a parameter that is passed. My code looks like this:
In index.js:
export var comments = (userId) => {
return new Promise((value) => {
axios.get('http://localhost:1000/getreviews/:userId')
.then((response) => {
console.log(response.data.comment);
})
})
}
In routes.js:
router.route('/:userId').get((req, res) => {
Users.find({user: req.params.userId})
.then((reviews) => res.json(reviews)
);
});
So I want to get relevant information. To give a higher-level idea of what is going on--there are multiple modals, and when a specific one is clicked I want to get specific information from the database, instead of getting all the information from the database and then do the extraction of relevant information in index.js based on the user's id. That way, I will be getting all the information on every modal click which is not efficient so I want to avoid it.

What is the problem exactly, is Users.find({user: req.params.id}) not returning the expected value? mongoose has findById which queries the db looking for the object with that specific id, in your case :
Users.findById(req.params.userId)
.then((reviews) => res.json(reviews)
);
edit: it seems like you're passing undefined as a parameter find, note that the name of the variable that is stored in params must be the same as the parameter you provided in your get method which is userId, so use req.params.userId instead.
edit2: js part
export var comments = (userId) => {
return axios.get(`http://localhost:1000/getreviews/${userId}`)
.then((response) => {
return response.data
})
}

Writing the GET request in a different way solved the issue:
axios({
method: 'get',
url: 'http://localhost:1000/getreviews/',
params: {
user: userId
})
Then I could access the userId in routes.js through req.query.user and it will give me the userId I just passed.

Related

How can I understand the use of query parameter in REST api?

As a learner, I am trying to call the rest api. For example, you can see and copy the url from api provider as they listed on that link page.
https://docs.api.jikan.moe/#tag/top/operation/getTopAnime
function App() {
const [topAnime, SetTopAnime] = useState([]);
useEffect(() => {
fetch(`https://api.jikan.moe/v4/top/anime`)
.then((response) => response.json())
.then((data) => {
console.log(data);
SetTopAnime(data);
})
.catch((err) => {
console.log(err.message);
});
}, []);
But the question is; this does not let me to call a specific data I want to call.
To do that, I need to add some query parameters as api page written for developer.
Now, I see several examples that someone set it as follows:
const getData = () => {
axios
**.get(`${apiTop}?sfw=true&limit=20`)**
.then((res) => {
return setData(res.data.data);
})
.catch((error) => {
console.log(error);
});
};
that .get method and following code makes sense. But how that developer who coded that line knew '?sfw=true&' such thing?
If I don't understand this; what topic could be the one I should review then? I believe I understand what promises and fetch are, but not sure focusing on 'query parameter' is the right thing to solve my problem.
tl;dr
To call a specific data from getTopAnime, how should I set query parameters? (with my understanding, https://api.jikan.moe/v4/top/anime/type/movie
or
https://api.jikan.moe/v4/top/anime?=query/type/movie
is the limit to expand the thoughts.
Thanks...
From the documentation of the API -- https://docs.api.jikan.moe/
There must be API documentation where you can read about these URI structures.
Though a real REST service sends you hyperlinks with URIs or URI templates which you follow, so you need to know what type of hyperlink watch for and the service gives you the URI structure. This is called HATEOAS constraint.

How to get single value from request response

I started writing a program that will automate user actions, by now it's meant to be an easier menu to make faster actions by just sending requests to the official website by clicks on my own page. (something like web-bot but not exactly).
My problem is when i send login request in response i get back user_id, server, session_id etc. And I need to save that session_id to make the other actions.
How can i save this to variable.
All in JavaScript.
I was looking in the internet since yesterday for an answer and i still can't find (or understand) how to get this
I tried
function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })
//There's the problem to solve
.then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id);
// I even tried the substring but 1. It won't work as I want because There are sometimes //more and less letters. 2. I get and error "Cannot read properties of undefined (reading //'substr')"
`session = obj;
session_id = session.substring(291,30)
console.log(session_id)`
It looks like you're using the text() method on the Response object returned from fetch(), which will give you a string representation of the response.
You probably want to be using the json() method instead, and from that you can get your session_id.
This guide has some more useful information that may help you: https://javascript.info/fetch
Ok it works now with
`async function login(){ let session = await fetch('url', {
//code
}
let result = await session.json();
console.log(result);
session_id = result.data.user.session_id;
user_id = result.data.user.id;`

How to send a variable to Backend - Mern Stack

I am trying to get some records from Mongo db based on a query. I completed the Back-end and it works well with the Postman but I do not know how to send the variable for the query from react front end to the back end.
There is a Client model class and I want to retrieve all the clients with a specific company ID which I will be sending from Front end on a button click.
Controller.js
exports.viewSpecificClients = async(req,res)=>{
const id = req.query.id;
console.log(id);
try{
const clients = await Client.find({clientCompanyName: id});
res.json({clients});
}catch(err){
console.log(err, 'clientsController.viewSpecificClients error');
res.status(500).json({
errorMessage: 'Please try again later'
})
}
};
Route
router.get('/', clientsController.viewSpecificClients);
I have to use Redux, so I tried do do this but I could only manage to display all the clients in the database (I do not know how to send the variable).
Action.js in Redux
export const getClients = () => async dispatch =>{
try{
const response = await axios.get('clients');
dispatch({
type: GET_CLIENTS,
payload: response.data.clients
});
}catch(err){
console.log('getClients api error:', err);
}
}
Can you please help me on how I can send the company id from front-end using redux - that is I want help with how to change the action function and also what do I have to do in the main.js file when the button is clicked ?
if you have access to companyId at the front end, all you need to do is
const response = await axios.get(`clients?id=${companyId}`);
assuming backend express is configured with query parser already.(by default)
may be you can have
const getClients = (companyId) => dispatch => {
const response = await axios.get(`clients?id=${companyId}`);
// above code here
}
let me know if you need further follow up.
You have two options there. First you pass the value of parameter as query string. The other option is to modificate your get request to a POST request where you can add request body. The post request is better if you try to pass more value like an object.

Problem with React making Get request to Node(express)

As the title says, i have a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:
So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"
async handleClickLicencia (event) {
event.preventDefault();
console.log(this.state);
console.log("licenciaInput: "+this.state.licenciaInput);
const datoBuscar = this.state.licenciaInput;
axios.get('http://localhost:3001/atletas/:licencia',this.state)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error)
})
And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:
const getAtletasByLicencia = (request, response) => {
const licencia = request.body.licenciaInput;
console.log("Request: "+request);
console.log("what the server gets: "+licencia);
// const licencia = request.licenciaInput;
const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
pool.query(sentencia, (error, results) =>{
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.
TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work
I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance
EDIT: Im also adding this code that i have which shows the route for my method in the server:
app.get('/atletas/:licencia', db.getAtletasByLicencia)
As #Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client
Change your request to:
axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
...
and your route (if you are using express) should look like this:
app.get('/atletas/:licencia', function (req, res) {
var licencia = req.params.licencia
...
})
As you are using request.body you should send a POST request with axios and add a body.

GetStream-IO - Dynamic Content With Realtime data

I am trying to figure out the best approach to storing data in get-stream, and how to pull real-time data on the client-side.
For example, let's say I have a user and they have an image. When they create a post, I add an activity:
const eventStreamPromise = eventStream.addActivity({
actor: event,
verb: 'post',
object: postId,
foreign_id: postId,
postText: 'some text',
user: 'internalUserId',
});
I would think I would use just a reference to the user, which is fine for when I do an initial load on the feed (I pull the feed from the client-side). But then, I'm not sure of the best way to get this data when I subscribe to the feed on the client-side.
this.getStreamListener = feed
.subscribe((data) {
console.log(data, 'got feed data, now what?');
})
.then(() {
console.log('now listening to changes in realtime');
})
.catch((error) => {
console.log('error', error);
});
Any advice is appreciated!
The anonymous function that is passed to the subscribe() method is invoked on every realtime update. The data parameter that's passed contains the activity along with some additional metadata like the timestamp.
Within that 'callback' function you can read the fields, e.g. the 'user' id, pull data from your back-end, update your client, etc.
Hopefully that helps?

Categories