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.
Related
I want to create a GET request that retrives data of particular user form user data and make that request from the browser as well
In browser need to get like this..
For example: localhost:3000/user/5
Then browser will print like
User details
User id:5
Name:Ann
Welcome to StackOverflow!
to retrieve the data of a particular user from DB.
here is a example
GET /users/{id}
router.get("/users/:id", async (req, res) => {
try {
const id = req.params.id;
const data = await Model.findById(id);
return res.send(data);
}catch(err){
return res.send(err);
}
});
id is the identifier of the user. the request will return the data of a particular user.
refer the docs
So I have two post methods in my express app and I am using an API SDK for these functions.
So the first post request runs and generates a random ID value. Then my 2nd post request I have to manually copy the ID from the console, then add it after the .deliveryQuoteAccept code
app.post("/get-quote", async (req, res) => {
const response = await client.deliveryQuote({
external_delivery_id: uuidv4(), //This creates unique ID value
});
res.send(response);
console.log("HERE IS THE ID", response.data.external_delivery_id)
)};
app.post("/accept-quote", async (req, res) => {
const response = await client.deliveryQuoteAccept(
"55acc96a-e5f2-45a6-8fce-cf62836244a0" //Manually typed the ID value here
);
res.send(response)
console.log(response.data.external_delivery_id) //This logs the ID from the get-quote post request
So the code above works perfectly fine.
My problem is I have to manually copy and paste that long ID value each time I create an order.
How do I add that value inside of my 2nd post request so that it will get the value each time automatically?
If I try to do this, it will say Cannot access 'response' before initialization
app.post("/accept-quote", async (req, res) => {
const response = await client.deliveryQuoteAccept(
response.data.external_delivery_id
); //This causes an error, can't access response before initialization
res.send(response)
console.log(response.data.external_delivery_id)
However, it will log the ID by logging the value outside of the parentheses. It won't work when I put the same code inside of the parentheses of the .deliveryQuoteAccept() code?
Any way to pass a value from one post request to another dynamically?
I am trying to update a collection in mongoDB after the user finishes some tasks. However, whenever I attempt to save the information and update mongo, I'm getting the error POST http://localhost:3000/updateSurvey/634124db6f 400 (Bad Request). Any ideas why my code isn't functioning correctly?
Backend js script
app.post('/updateSurvey', async (req, res) => {
try {
await client.connect();
var db = client.db('Admin_Db');
var collection = db.collection('Survey');
await collection.findOneAndUpdate({"_id": ObjectId(req.body.id)}, {completion: req.body.completion});
res.send("updated");
} catch (error) {
console.log(error);
res.status(400).send(error);
}
});
Main.js (this is how I am fetching the data from mongo)
fetch("http://localhost:3000/updateSurvey", {
method:'POST',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({id: surveyID, completion: true})})
.then(response=>{response.text()})
.catch(function(err){console.log("Fetch Problem: " + err)});
You don't have a route http://localhost:3000/updateSurvey/634124db6f exposed on your server. Therefore the 404 error. Since you are using a post call, just pass the surveyID in your body when making the post call using fetchAPI instead of sending it as a query param.
And make sure http://localhost:3000/updateSurvey is the route to which your are sending your data, without the surveyId in the URL.
Edit
Edits made as per request received in comments.
collection.findOneAndUpdate({"_id": id)}, {completion: req.body.completion});
should be:
collection.findOneAndUpdate({"_id": new ObjectId(id))}, {completion: req.body.completion});
_id is of type ObjectId in MongoDB. You are passing id as string. This should most likely be the error from what I can gather by the code shared in your question. You can cast a string to ObjectId by using the ObjectId class provided by the Mongo Driver for node. Even mongoose provides this class.
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.
This the endpoint in my api that I am trying to access
router.get('/:id', [jsonParser, jwtAuth], (req, res) => {
return Teams.find().sort({creator: req.params.id})
.then(teams => res.status(200).json(teams))
.catch(err => res.status(500).json({message: 'Internal server error'}));
});
The fetch will probably look something like this?
function viewProfile() {
const base = '/api/teams/';
const id = idFromJwt;
const url = base + id;
return fetch(url)
.then(res => res.json())
.then(response => {
//takes response and modifies DOM
populateProfile(response);
})
.catch(err => console.log(err));
}
First of all, assuming you're using ExpressJS I do suggest leveraging express-jwt middleware to handle requests authentication and issuing new Tokens.
What you need to bear in mind is that, you need to include the userId when you authenticate the user in the JWT payload in order to be able to retrieve it from the payload afterwards.
When user is authenticated, you have to store the token in the state of your application or in the localStorage or sessionStorage.
In case you want to decode the token on the front-end side and then send it to the API, you can use a simple module called jwt-decode to achieve that:
const jwtDecode = require("jwt-decode");
const token = window.localStorage.getItem("token"); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWQiOiIxMjM0NTY3ODkiLCJpYXQiOjE1MTYyMzkwMjJ9.gHqSxzWpdOUL1nRAqUJg2CtjsEZZi8FLikD41i639zY
const tokenPayload = jwtDecode(token).id; // "123456789"
Please bear in mind that in case you decided to use express-jwt you need to also send the token in the headers of the request as authorization to authenticate.
Hope it helps. :)