Frontend to Backend POST request is not yielding the data I want - api

I'm currently working on a project using a React frontend and an Express backend. Currently, when I make a GET request to retrieve data from the backend, everything is working fine. However, I'm unable to POST data to the backend and gain access to the data that's being sent. I'm getting an OK message so the request is going through, but when I log the request data in the backend, I get a message like this which is a jumble of random fields.
Here is the code snippit in the front end for the POST request
const makePost = (data) => {
fetch('http://localhost:5000/api', {
method: 'POST',
headers: {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"},
body: JSON.parse(JSON.stringify(data))
}).then(function(response){
console.log(response.text())
})
}
Here is my backend which handles the POST request
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors({
origin: '*'
}));
app.get('/api', (req,res) => {
res.json(menuItems);
});
app.post('/api', (req,res) => {
console.log(req)
})
app.listen(5000, () => console.log("server started on port 5000"));
In the code snippit above, console.log(req) is what was logged in the screenshot linked above.

In your Express server POST API, you are not returning any data, it may cause problems. This is a sample POST API using Axios, Express, React, and MongoDB.Hope it would help you.
//POST API
app.post('/services',async(req,res)=>{
const service = req.body;
const result = await servicesCollection.insertOne(service);
console.log(result);
res.send(result)
});
In client-side POST api:
const onSubmit = data => {
axios.post('http://localhost/services', data)
.then(res=>{
if(res.data.insertedId){
alert('data added successfully');
reset();
}
})
sample post API:
app.post('/book', (req, res) => {
const book = req.body;
// Output the book to the console for debugging
console.log(book);
books.push(book);
res.send('Book is added to the database');
});
Pls take a look at this link: https://riptutorial.com/node-js/example/20967/post-api-using-express

Related

AXIOS GET request to instagram not working in prod

I am stuck for a few hours and I can't find an answer.
It's a very simple request that works fine in the browser (it returns a JSON answer), for example :
https://www.instagram.com/eurosportfr/channel/?__a=1
In dev the code:
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/instagram', (req, res) => {
async function getInstagramFeed() {
await axios
.get('https://www.instagram.com/eurosportfr/?__a=1')
.then((response) => {
console.log(response);
res.write(`${JSON.stringify(response.data)}`);
res.end();
})
.catch((err) => {
console.log(err.response);
res.write('<h1>ERROR GRAVE</h1>');
res.write(err.response);
res.end();
});
}
getInstagramFeed();
});
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
The result in DEV ENV is JSON data with all what I need.
But in production, it doesn't return me the JSON. Instead it returns me an HTML page...
You can try it here: (I display in the body the result)
https://corsmiddleware.vercel.app/instagram
When I try another api request with another API client, it works just fine in prod, example :
https://corsmiddleware.vercel.app/test
Any idea ??
Thanks
This request now requires authentification. It was working in the past, and it's still actually working here in Morocco where I am, but this solution is not reliable.
The solution is to follow the instructions on facebook :
https://developers.facebook.com/docs/instagram-basic-display-api/

Calling an api and return these values in Nodejs

I am trying to build a small website. In that i using React for frontend, Nodejs for backend, and some third party api. Here my idea is, first to post the form data to nodejs. And from then i accepting that data in node and need to call an external api. For this purpose i am using axios. After receiving values from my api i have to send that value back to react application. And when i run my code in postman, the output is {}. I think that i am not getting values from my api but dont know how to resolve this. And i am new to these technologies. Someone pls help me to sort out this problem. Thanking you in advance. Here is my what i have tried so far.
const express = require('express');
const axios = require('axios');
const router = express.Router();
const request = require('request');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended : false}));
router.get('/', (req, res) => {
res.send(" Express Homepage is running...");
});
async function callApi(emailid, pswd) {
return axios({
method:'post',
url:'http://51.X.X/api/login',
data: {
"email": `${emailid}`,
"password": `${pswd}`
},
headers: {'Content-Type': 'application/json' }
})};
callApi().then(function(response){
return response.data;
})
.catch(function(error){
console.log(error);
})
app.post('/api/login', (req, res) => {
let emailid = String(req.body.email);
let pswd = String(req.body.password);
const data = callApi(emailid, pswd);
if(data) {
res.send(data);
}else {
res.json({msg : " Response data not recieved.."})
}
});
use async/await syntax to handle asynchronous calls
app.post('/api/login', async (req, res) => {
let emailid = String(req.body.email);
let pswd = String(req.body.password);
const data = await callApi(emailid, pswd);
if(data) {
res.send(data);
}else {
res.json({msg : " Response data not recieved.."})
}
});
The problem is you are not waiting for async call to finish.
use async-await as mentioned in official doc https://www.npmjs.com/package/axios
function callAPI(){
const response = await axios({
method:'post',
url:'http://51.X.X/api/login',
data: {
"email": `${emailid}`,
"password": `${pswd}`
},
headers: {'Content-Type': 'application/json' }
})};
return response
}
app.post('/api/login', async (req, res) => {
let emailid = String(req.body.email);
let pswd = String(req.body.password);
//add try catch to catch exception
const data = await callApi(emailid, pswd);
if(data) {
//check for response from axios in official doc and send what data you
want to send
res.send(data);
}else {
res.json({msg : " Response data not recieved.."})
}
});

Forward decoded POST data to other URL using Express

Some background information:
I have a temperature sensor which is connected via LoRaWAN.
The data from the sensor is encoded, but the manufacturer of the sensor provides a decoder (node app).
I want to show the data in Thingsboard.
Now I was thinking to build a simple express API (I'm new to Express) as a kind of middleware.
The only purpose is to receive the encoded data, decode it (output is in JSON format), and pass it on to Thingsboard.
With the last step I need some help. This is my route:
const decoder = require('../helpers/decoder');
module.exports = app => {
app.post('/', (req, res) => {
const data = {
type: req.body.productType,
payload: req.body.payloadValue
};
const jsonData = decoder.decode(data.type, data.payload);
// jsonData needs to be forwarded/redirected Thingsboard
});
};
Can anyone point me in the right direction, how to pass on the "handled" POST data and pass it on to another URL (Thingsboard HTTP endpoint URL)
Thanks in advance!
💡 This is not the best practice, but if you want to read some data from some route in another route without passing them when the route was called then you can try this code below: 👇
const express = require('express');
const app = express();
app.post('/', (req, res) => {
app.locals['decoder'] = { data: "This is my decoder data"};
res.send('Successfully to add decoder data');
});
app.get('/', (req, res) => {
res.send(app.locals['decoder']);
} )
app.listen(3000, () => {
console.log('Server is up');
});
⚠️ It should be noted that the code above is only an example of how to read data from one route on another route.
Another option:
👨‍🏫 You can create a middleware that is used to decode your payload and use the middleware on each route that requires the results of the decoded payload.
⚠️ But, it should be noted that for this problem, you must leave a payload on each route that requires decoded results, so that it can be decoded.
Updated: Passing Data To External Endpoint
💡 If You want to pass the data to an external endpoint or another website, see code below: 👇
const axios = require('axios');
app.post('/', (req, res) => {
const decoder = { data: "This is my decoder data"};
// method of external-endpoint: e.g: POST
axios.post('https://www.example-website.com/api/v1/example-endpoint', decoder)
.then(response => {
console.log(response);
}).catch(ex => {
console.log(ex);
})
})
You can use that route above in the example express server in addition to this answer.
I hope it's can help you 🙏.

http post request to an api using axios in nuxtjs shwoing net::ERR_HTTP2_PROTOCOL_ERROR

I have made an API using lumen and all POST,GET Methods are working well in localhost and also works GET request when hosted on live server but unfortunately POST request are not working and shows the error as
net::ERR_HTTP2_PROTOCOL_ERROR
The POST request is working well in POSTMAN
async submitForm(){
const config = {
headers: { 'content-type': 'application/json','Accept':'application/json','Access-Control-Allow-Origin':'*'}
}
let formData = new FormData();
formData.append('name', this.name);
formData.append('email', this.email);
formData.append('phone', this.phone);
formData.append('message', this.message);
await this.$axios.$post('https://myurl',formData,config)
.then((response) => {
this.success = 'Thank you !!';
})
.catch((error) => {
this.error = 'Unable to submit . Please try again later .';
});
}

github apps - webhook request doesn't have payload

First, here are my github apps events:
And I set up my webhook URL(blahblah.com/watch) and express server like this:
const express = require("express");
const app = express();
app.post("/watch", (req, res) => {
console.log(req);
});
app.listen(3000, () => console.log("opened"));
The problem is that when I create an issue comment, the request of webhook arrives in my express server but has no body or payload.
The request is here:
LOOK AT THAT! THERE IS NO PAYLOAD!
What should I do? What am I doing wrong?
I thought req must have a property body or payload. How can I access the payload of the request?
Actually, the problem is not because of webhook request, but my express code!
I've resolved the problem by modifying my code like this:
app.post("/watch", (req, res) => {
let body = "";
req.on("readable", () => {
body += req.read();
});
req.on("end", () => {
console.log(body);
})
});
I didn't know that there is readable event and end event to handle a request!
I've got an idea from this answer.