Cant read post from Fetch in node - node.js

I'm posting the data {id: "abc123", text: "sometext"} to a node API. Posting from a component with action call:
export function addTextToAPI(inputData) {
return(dispatch) => {
console.log(inputData),
dispatch(addText(inputData))
fetch(myapi, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
data: inputData
})
.then(res => res.json())
}
}
console.log(inputData) is {id: "abc123", text: "sometext"}
node:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/addtest', (req, res) => {
console.log(req.body); // <= returns blank object {}
console.log(req.body.data); // <= returns undefined
console.log(req.query); // <= returns blank object {}
console.log("test added");
});
app.listen(3000);
I want to be able to read the inputData in req. How do I do that? I want to be able to read the inputData in req. How do I do that?

To post data you need to pass in a body param to fetch.
This should work:
export function addTextToAPI(inputData) {
return(dispatch) => {
console.log(inputData),
dispatch(addText(inputData))
fetch(myapi, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(inputData)
})
.then(res => res.json())
}
}

Related

How to hide my API Key in a POST request?

I want to hide my API key when I am making a post request from my browser. I need to input a number plate and send the request to the API and the API responds me with details about it. I have managed to get this working with a GET request to another API by using nodeJS but I can't manage to make it work with a post request. Keep in mind the request needs information from my input field in the browser which is the registration number of the vehicle to send me information back about it.
Here is my function in my browser JS file.
const searchBtn = document.getElementById("search-btn")
function startFetch() {
let plate = document.getElementById("plate").value
let reg = {registrationNumber: `${plate}`}
fetch(`https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': `my key is here`,
},
body: JSON.stringify(reg),
})
.then(response => response.json())
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
searchBtn.addEventListener("click", startFetch);
Any help and method would be appreciated. Thanks in advance.
For anyone in the same boat. I have managed to achieve what I want.
Client side JS file:
function startFetch() {
let plate = document.getElementById("plate").value
let reg = {registrationNumber: plate}
fetch(`http://localhost:3000/v`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(reg),
})
.then(response => response.json())
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
And the backend using Express, NodeJS, body-parser and axios
require("dotenv").config()
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const axios = require('axios');
app.use(bodyParser.json());
app.use(express.static("src"))
//Env vars
const API_URL = process.env.API_URL
const API_KEY = process.env.API_KEY
app.post('/v', (req, res) => {
const body = req.body;
// Make a request to the backend API
axios.post(API_URL, body,
{
headers: {
"Content-Type": "application/json",
'x-api-key': API_KEY
}
}
)
.then((response) => {
// Return the response from the backend API to the client
res.send(response.data);
})
.catch((error) => {
// Handle any errors
res.status(500).send(error);
});
});
app.listen(3000, () => {
console.log('API proxy server is listening on port 3000');
});
You are already sending the body.
A very minor modification to you code:
function startFetch() {
let plate = "abc123";
let reg = { registrationNumber: `${plate}` };
fetch(`https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": `my key is here`,
},
body: JSON.stringify(reg),
}
);
}
startFetch();
You can see your api-key in the header (though you should never send secret via http):
Then in the body (in chrome they call it payload):

how to perform operations with json string from axios?

Background
I am passing variable from my frontend HTML file using axios
var idToken1 = result.getIdToken();
axios({
method: 'post',
url: '/trial',
data: idToken1,
headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
in my app.js under route getting this as output,here all the values are present in key and key values is empty. so i think i need a way to parse those keys first
{
'{"payload":{"cognito:username":"jatin","exp":1620965984,"iat":1620962384,"email":"xxxx#gmail.com"}}': ''
}
i want to extract "email":"xxxx#gmail.com"
update: in app.js i am already using express native parser app.use(express.json()); app.use(express.urlencoded({ extended: true }));`
A parser is required if you want to get the http body as object:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
Then you can use req.body to get the http body sent by your html web:
app.post('/trial', function(req, res) {
var email = req.body.payload.email;
//etc
});
The problem was with axios. axios needed object to be send as json object.
var idToken1 = result.getIdToken();
the following code results in proper JSON object in my backend
axios({
method: 'post',
url: '/trial',
data: { idToken: idToken1 },
headers: { 'Content-Type': 'application/json' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
The Problem cause is 'Content-Type'
is should be 'application/json'
axios({
method: 'post',
url: '/trial',
data: idToken1,
headers: { 'Content-Type': 'application/json' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

Receive JSON response from POST request in Node.js

I'm trying to authorize using Spotify in NodeJS. This is my code:
app.get('/auth', function(req, res){
if(req.query.error){
res.redirect('/error');
};
var resdata;
const data = querystring.stringify({
'grant_type':'authorization_code',
'code': req.query.code,
'redirect_uri': 'https://<MYURL>/auth',
'client_id': process.env.ID,
'client_secret': process.env.SECRET
})
const options = {
hostname: 'accounts.spotify.com',
port: 443,
path: '/api/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
}
const authreq = https.request(options, authres => {
authres.on('data', d => {
resdata += d;
})
authres.on('end', d => {
res.send(resdata);
})
})
When I make the request, I get this response:
undefined{\"access_token\":\"<TOKEN>\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"refresh_token\":\"<TOKEN>\",\"scope\":\"playlist-read-private user-modify-playback-state\"}
How do I turn this into JSON?
I want to do this in plain NodeJS, without any modules if possible.
Assign resdata to empty string like this instead of keeping it undefined.
var resdata = '';
And in your end listener change it to
authres.on('end', d => {
res.send(JSON.parse(resdata));
})
You could use JSON.parse(result.slice(9))
But there's probably a better way.

Node.js Http request returns 400 error when send Unicode(Bangla) character in body

I am having an issue when send Http request to Infobip SMS APi with Unicode character in body. I tried with axios and request module but both are not working for unicode value but it's working for normal english character. here is the code
var express = require('express');
var request = require('request');
var app = express();
var url = 'http://api.infobip.com/sms/2/text/single'
var options = {
method: 'post',
data: {
'from': 'ME',
'to': '(555) 555-1234',
'text': 'ওহে বিশ্ব',
},
headers: {
'authorization': 'Basic AUTH_KEY',
'content-type': 'application/json',
'accept': 'application/json'
},
url: url
}
request(options, function (err, res, body) {
if (err) {
console.log('Error', err);
}
console.log(res, body);
})
you can check it by axios
var express = require('express');
var app = express();
var axios = require("axios");
const config =
{
headers:
{
'authorization': 'Basic AUTH_ID',
'content-type': 'application/json;charset=UTF-8',
'accept': 'application/json'
}
};
axios.post('http://api.infobip.com/sms/2/text/single',
{
'from': 'ME',
'to': '+8801XXXXXX',
'text': 'ওহে বিশ্ব',
},
config,
)
.then(function(response) {
console.log(response.data)
})
.catch(function(error) {
console.log(error)
})

How to show the success response from node server on react-redux framework

I am making a demo react-redux app for the basic understanding of redux and its server is made on nodeJS. I have made a simple form which gets submitted and the server response is res.send('FORM SAVED'). In front-end, I make the post request but is not able to see the response that returns, be it the success response.
My server controller that responds when form details are saved.
export const postData = (req, res) => {
let p = new PostData();
p.name = req.body.name;
p.emp_id = req.body.emp_id;
p.age = req.body.age;
p.dept = req.body.dept;
p.phone = req.body.phone;
p.gender = req.body.gender;
p.save(((err) => {
if (err){res.send(`Error in uploading: ${err}`);}
else {res.send('Form saved');}
}));
}
This is my action:-
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then((post) => {
console.log('post:', post);
dispatch({
type: NEW_POST,
payload: post
})
})
}
This is how I call this in component after clicking submit:-
onSubmit = (e) => {
e.preventDefault();
let postData = {
name: this.state.name,
emp_id: this.state.emp_id,
dept: this.state.dept,
gender: this.state.gender,
age: this.state.age,
phone: this.state.phone
}
this.props.createPost(postData);
}
I want to get the response string ('Form saved') but I don't know how to read that. Can anyone help? Thanks in advance
fetch returns a raw response object. To get an expected data you should call a .json() method on raw response object which is returned by fetch, like below:
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json()) // add this line
.then((post) => {
console.log('post:', post); // you should get an object with `Form saved` or something similar to it
dispatch({
type: NEW_POST,
payload: postData // replace it to the input parameter
})
})
}
Using async/await it becomes more readable:
export const createPost = (postData) => async (dispatch) => {
// send postData to server
const rawResponse = await fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
// we are done with server but we need one more step
// turn a raw response to readable JS object
const message = await rawResponse.json()
// message from server response
console.log('Message ', message);
// store same object as we sent to server in redux store
dispatch({ type: NEW_POST, payload: postData });
}
Hope it helps

Resources