Taking response from Node.js in Angular - javascript

I am trying to fetch data from Mongodb and i want that data to show up on my web page.The problem is i don't know how to send the whole fetched object to a specific port (the response) so that i'll be able to fetch it from Angular and how will i be able to access data from Angular
Fetching data from Mongodb
app.get('/api/getdata',async (req,res) =>
{
const {value} = req.body
const resp=await person.find({value})
if(!resp){
console.log('not found')
}
else{
//this needs to be done
}
})

Please, have a look at express API reference
then your code would look like :
app.get('/api/getdata', async (req,res) => {
const {value} = req.body
const resp = await person.find({value})
if (!resp) {
res.status(404).send('not found')
}else{
// give your data to express response to the http request
res.json(resp); // or res.send(resp);
}
});

Related

Get Request returning 404

I'm using the open weather API to make a get request based on a zipcode passed in as a query parameter. When I run the endpoint in Postman I receive a successful response and can see the data. When I run the request from my app (even with a hard coded value for testing) I get a 404 not found.
Endpoint from my server file:
const weatherCtlr = require('./controllers/weatherController);
app.get('/api/weather', weatherCtlr.getWeather);
My Controller
const axios = require('axios');
const {APIKEY} = process.env;
module.exports ={
getWeather :(req, res)=>{
const {zipcode} = req.body;
axios.get(`https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&APPID=${APIKEY}`)
.then(()=>{
res.sendStatus(200);
})
.catch(err=>console.log(err))
}
}
Client Side, (axios is imported)
getWeather =()=>{
const {zipcode} = this.state.canyon;
axios.get('/api/weather', {zipcode})
.then(res=> this.setState({weather: res.data)})
.catch(err=>console.log(err))
}
I call the method on an on click
onClick={()=>this.getWeather()}
I'm not really sure what the issue is. I know the api key is good because I when I test my actual endpoint localhost.../api/weather and send a zipcode in the body it works.
What stands out is that you send a body to your server using get:
getWeather =()=>{
const {zipcode} = this.state.canyon;
axios.get('/api/weather', {zipcode})
.then(res=> this.setState({weather: res.data)})
.catch(err=>console.log(err))
}
The GET method does not accept a body. Then on the server side you parse it out like this:
const {zipcode} = req.body;
I would be very surprised if you actually get that zipcode. Most likely that will be undefined.
So I would try changing your client side request to:
axios.post('/api/weather', {zipcode})
Once you get the response back from the API, you can send it back to your app like so:
axios.get(`https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&APPID=${APIKEY}`)
.then((response) => {
res.json(response.data);
})
.catch(err => {
console.log(err);
res.json({msg: 'Error'})
})

Redirect and send data from Node server back to React

I have a NodeJS server in which I'm using Express and a front-end with React. I want to know how to send data from the server to the front-end. All the solutions I've seen use a call from the front-end, then the server answers, and finally the front-end gets the data. My problem is that I don't have a call from the front-end, but a call back-end (router.get('/callback')) to back-end (router.get('/receipt/:id')). Here is the code for a better understanding.
router.get('/callback', (req,res) => {
const ref = req.query.reference;
verifyPayment(ref, (error,body)=>{
if(error){
//handle errors appropriately
console.log(error)
return res.redirect('/payment/error');
}
response = JSON.parse(body);
const data = _.at(response.data, ['reference', 'amount','customer.email', 'metadata.full_name']);
[reference, amount, email, full_name] = data;
newDonor = {reference, amount, email, full_name};
const donor = new Donor(newDonor);
donor.save().then((donor)=>{
console.log("--------------- donor" + donor);
if(!donor){
return res.redirect('/payment/error');
}
res.redirect('/payment/receipt/' + donor._id);
}).catch((e)=>{
res.redirect('/payment/error');
});
});
});
router.get('/receipt/:id', (req, res)=>{
const id = req.params.id;
Donor.findById(id).then((donor)=>{
if(!donor){
res.redirect('/payment/error')
}
// I'VE TRIED THIS
//res.redirect('http://localhost:3000/#' + donor.full_name);
/*
AND THIS
console.log(donor.full_name);
const resp = axios.post('http://localhost:3000', {params: {donor.full_name}});
console.log(resp.data);
*/
}).catch((e)=>{
res.redirect('/payment/error')
});
});
Now what I want is to come back to the front-end (a index.js using React) and get the data and show it. Any idea?????
You need to understand how the data pass between the Node server and your React App.
We use JSON objects to pass the data server to the client (look for REST APIs for more info)
Try this in your server
router.get('/receipt/:id', (req, res)=>{
const id = req.params.id;
Donor.findById(id).then((donor)=>{
if(!donor){
res.redirect('/payment/error')
}
//How to send the data
res.status(200).json({
message: "Data returned Successfully",
Fullname:"donor.full_name"
});
}).catch((e)=>{
res.redirect('/payment/error')
});

Node JSON-Server returning MOCK post response

I'm trying to use https://www.npmjs.com/package/json-server as a mock backend, I'm able to match URLs for get, but how can i return some mock-response for POST calls.
Like for create user URL will be like
URL - http://localhost:4000/user
Method - POST
Request Data - {name:"abc", "address":"sample address"}
expected response -
httpStats Code - 200,
Response Data - {"message":"user-created", "user-id":"sample-user-id"}
In Some Cases I also want to send custom http codes like 500,423,404,401 etc.. depending upon some data.
Biggest problem is that my code is not returning anything response for POST, its only inserting records in JSON
By default POST requests through json-server should give a 201 created response.
If you need custom response handling, you might need a middleware to get hold of req and res object.
Here I'm adding a middleware to intercept POST requests and send a custom response. You could tweak it to your specific case.
// Custom middleware to access POST methods.
// Can be customized for other HTTP method as well.
server.use((req, res, next) => {
console.log("POST request listener");
const body = req.body;
console.log(body);
if (req.method === "POST") {
// If the method is a POST echo back the name from request body
res.json({ message:"User created successfully", name: req.body.name});
}else{
//Not a post request. Let db.json handle it
next();
}
});
Complete code (index.js)..
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults();
server.use(jsonServer.bodyParser);
server.use(middlewares);
// Custom middleware to access POST methids.
// Can be customized for other HTTP method as well.
server.use((req, res, next) => {
console.log("POST request listener");
const body = req.body;
console.log(body);
if (req.method === "POST") {
// If the method is a POST echo back the name from request body
res.json({ message:"User created successfully", name: req.body.name});
}else{
//Not a post request. Let db.json handle it
next();
}
});
server.use(router);
server.listen(3000, () => {
console.log("JSON Server is running");
});
And you can start json-server using node index.js

access react route params in server side

i came up with this problem with ReactJS and ExpressJS: So basically user uploads some info on /info route with React & axios. then user gets route params from server side to redirect to:
axios.post('/info', SomeData)
.then(res => res.data)
.then(data =>{
window.location.replace(`/info/${data.id}`)
})
this is piece of cake but when user redirects to that page problem occurs, i need to get data from that page. i can get route params and perform request on client side like this:
componentDidMount(){
const { match: { params } } = this.props;
axios.get(`/api/info/${params.id}`)
}
but how can i get request on server side? how can express access that "id" to search it in database and query data with it to send back to client? like:
app.get('/api/info/:id', async (req,res)=>{
await db.find({id: req.params.id}, (data) =>{
res.status(200).send({data})
})
})
Any help? Thanks!
From the component itself same as the GET use your param and call your service same thing to POST
postUserInfo = () => {
const userInfo ={};
axios.post(`/api/info/${params.id}`,userInfo).then(()=>{
console.log("user info posted");
})
}
Example:
<Form onSubmit={this.postUserInfo}> </form>

How to reroute a payload from a 3rd party POST to a client via GET

In my Express app I am receiving a payload from an external POST request:
router.post('/liveReleaseStore', (req,res) => {
let thing = req.body.myPayload
...
I also handle a GET request from my client:
router.get('/liveReleaseStore', (req, res) => {
let myResponse = ...
res.send(myResponse);
});
I need to reroute the payload so that when my client sends a GET to the server I am able to send back the data or tell the client that I haven't received any data yet.
What is the best way to about about this?
Thanks
You could initialize the data outside the two functions to null. And then send the data if it's been initialized by the post function.
let thing = null;
router.post('/liveReleaseStore', (req,res) => {
let thing = req.body.myPayload
...
}
router.get('/liveReleaseStore', (req,res) => {
if (thing === null)
return res.send('no data yet');
res.send(thing);
}

Categories

Resources