How to get axios post data request on nodeJs [duplicate] - node.js

This question already has answers here:
How to access the request body when POSTing using Node.js and Express?
(15 answers)
Closed 2 years ago.
I am trying to send a post request using Axios and I also want to access the data from the server. My code is
axios({
method: 'post',
url: '/register/',
headers: {'Content-Type' : 'application/json'},
body: JSON.stringify({fname, lname, username, email, pass})
})
.then((res) => {
console.log(res)
})
.catch(err => {
console.log(err)
})
// and my backend code is
const express = require('express')
const router = express.Router()
router.post('/', async (req, res, next) => {
const firstname = ''
})
Request is send properly and my server also accepts the request. but i do not know how to get the values from my server.
please help me. code is working fine just help me in getting the values on server side code

Unlike fetch, axios does not require you to stringify the body of the post request. You can just post like so:
axios({
method: 'post',
url: '/register/',
headers: {'Content-Type' : 'application/json'},
body: {fname, lname, username, email, pass}
})
...
Assuming you are posting to the correct endpoint (e.g. /register), on the server side, you would access it this way:
router.post('/register', (req, res) => {
const fname = req.body.fname;
...
})
Note that this assumes your backend is properly configured. If all you're running is the code you showed, it won't work as you would need stuff like:
const app = express();
app.use(express.json());
...
...
app.listen(YOURPORT, () => {
console.log(`Listening to requests on port YOURPORT...`);
});

Related

Axios frontend doesn't seem to pass request parameters to backend

I have this hook on react for my frontend to perform http requests to get data to show on page
useEffect(() => {
const options = {
method: "GET",
url: `http://localhost:8080/api/v1/postersgrid`,
params: { query: props.query },
};
axios
.request(options)
.then((res) => {
console.log(res);
setResults(res.data.results);
setTotalPages(res.data.total_pages);
setSuccessfulRequest(true);
})
.catch((err) => {
console.log(err);
setSuccessfulRequest(false);
});
}, [props.query]);
as you can see that endpoint is mine because i made a little backend for my app
const express = require("express");
const cors = require("cors");
const axios = require("axios");
const PORT = 8080;
const app = express();
app.use(cors());
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
app.get("/api/v1/postersgrid", (req, res) => {
const options = {
method: "GET",
url: `https://api.themoviedb.org/3/search/movie?api_key=${APIKEY}&query=${req.query}`,
};
axios
.request(options)
.then((response) => {
res.json(response.data);
})
.catch((error) => {
console.log(error);
});
});
this backend communicates with an api of which i have the api key.
What i want is:
frontend queries backend where api key is hidden
backend queries api and returns data to frontend
Now the problem is when i try to pass parameters from frontend to backend
const options = {
method: "GET",
url: `http://localhost:8080/api/v1/postersgrid`,
params: { query: props.query },
};
here i try to pass it to backend but as soon as i use it in the url to perform http requests to the api it's like it's undefined or null
url: `https://api.themoviedb.org/3/search/movie?api_key=${APIKEY}&query=${req.query}`,
to prove this works, if i change the query to be static
url: `https://api.themoviedb.org/3/search/movie?api_key=${APIKEY}&query=war`
everything works as intended, where am I wrong? btw I'm doing all of this instead of performing requests directly from frontend to hide my api key correctly
Had to change this
url: `https://api.themoviedb.org/3/search/movie?api_key=${APIKEY}&query=${req.query}
to this
url: `https://api.themoviedb.org/3/search/movie?api_key=${APIKEY}&query=${req.query.query}

Send params from frontend to be used in a NodeJS Get request

I am trying to pass data to my Node.js backend in order to use it in a get request to an API.
For example:
Server.js
const PORT = 8000
const axios = require('axios').default
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
require('dotenv').config()
app.use(express.json())
app.get('/convertedAmount', (req, res) => {
const contentBody = req.body
const options = {
method: 'GET',
url: 'https://currency-converter5.p.rapidapi.com/currency/convert',
params: {format: 'json', from: contentBody.primaryCurrency, to:
contentBody.secondaryCurrency, amount: contentBody.primaryCurrencyAmount},
headers: {
'x-rapidapi-host': process.env.RAPIDAPI_HOST,
'x-rapidapi-key': process.env.RAPIDAPI_KEY,
},
}
axios
.request(options)
.then((response) => {
res.json(response.data)
})
.catch((error) => {
console.error(error)
})
})
app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))
The issue is, I don't know how to pass data to the backend from the frontend, without making it a POST request. But that doesn't work if I make a POST request to the rapidAPI url. So the backend needs to stay the same.
My question is, how would I write the frontend part for this?
Using a POST request in the frontend sends the data with the req.body, but I cant get the data to display in my browser on localhost:8000/convertedAmount.
Thank you
My attempt is:
Frontend.js
...
axios.post('/convertedAmount', {
primaryCurrency: 'USD',
secondaryCurrency: 'GBP',
primaryCurrencyAmount: 1
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
})
...
You shouldn't be trying to send data in the body (such as in req.body) through a GET request. That is what a POST request is for.
With a GET request, you should pass data (such as a user id) as a parameter. Basically, in the url string.
FRONTEND
axios.get("/convertedAmount/USD/GBP/1")
BACKEND
app.get("/convertedAmount/:primaryCurrency/:secondaryCurrency/:primaryCurrencyAmount", (req, res)=>{
console.log(req.params.primaryCurrency);
console.log(req.params.secondaryCurrency);
console.log(req.params.primaryCurrencyAmount);
});
Alternatively, you could use query strings, which would look like this:
FRONTEND
axios.get("/convertedAmount?primaryCurrency=USD&secondaryCurrency=GBP&primaryCurrencyAmount=1")
BACKEND
app.get("/convertedAmount*", (req, res)=>{
console.log(req.query.primaryCurrency);
console.log(req.query.secondaryCurrency);
console.log(req.query.primaryCurrencyAmount);
});

Error 400 when making POST request to Spotify API with Axios on Express.js

I'm trying to retrieve an access token from the Spotify API when making a post request with axios on an Express back end server. So far I have been unsuccessful. I'm getting the following error:
data:
{ error: 'unsupported_grant_type',
error_description:
'grant_type must be client_credentials, authorization_code or refresh_token' } } }
I've already tried to change 'data' property for 'grant_type' to 'params' but it's still not working. Any advice would help.
const express = require('express');
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const port = 3000;
const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;
app.get('/spotify-authorization', (req, res) => {
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: {
grant_type: 'client_credentials'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic ' +
Buffer.from(client_id + ':' + client_secret).toString('base64')
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
res.send('successful response received!');
});
app.listen(port, () => console.log(`Express app listening on port ${port}!`));
I want to be able to retrieve the access token in the response from the Spotify API. Please help!
From axios docs : By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
For Nodejs you can use the querystring module as follows:
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
So, in your case you could try data: querystring.stringify({ grant_type: 'client_credentials' })
I can't leave a comment due to low reputation, but 1556089774's answer should be the accepted answer. I've spent over 4 hours researching as to why it wasn't working since Spotify's iOS sdk points to https://glitch.com/~spotify-token-swap as an example which does NOT WORK. Adding the stringify to the data part of the request makes it work:
data: querystring.stringify ({
grant_type: "authorization_code",
redirect_uri: SPOTIFY_CLIENT_CALLBACK_URL,
code: authorization_code
})

How to use API path param in npm request & request-promise libraries

In my NodeJS/Express app, I have API implementation which calls another external API.
For this, I am using npm request & request-promise libraries
How can I call API's that has path parameter?
const express = require('express');
const router = express.Router();
const rp = require('request-promise');
router.post('employee/:id', (req, res) => {
const id = req.params.id; // I dont know how to use this in request library
handleRequest(req, res);
})
function handleRequest(req, res) {
const id = req.params.id; // I dont know how to use this in request library options?
var options = {
method: req.method,
uri: 'http://api.anotherhost.com/external/'+ req.path,
body: req.body,
qs: req.query,
json: true
};
rp(options)
.then((success) => res.send(success))
.catch((err) => res.status(err.statusCode).send(err.message));
}
https://github.com/request/request
https://www.npmjs.com/package/request-promise
Update:-
This code so far works fine for other calls without path parameter.
Since request doesn't provide an option to add path parameters you have to format your request uri to include them, you can simply use string literals to do this:
const id = req.params.id;
var options = {
method: req.method,
uri: `http://api.anotherhost.com/external/${id}`,
body: req.body,
qs: req.query,
json: true
};
Keep in mind you must verify that the id format is valid.

400 (Bad Request) Second Time When Posting to API

Currently, I have run into an issue that I've been stuck on all day. In essence, I am trying to get a login session for an account through the Roblox authentication API. It works the first when I post from my server to their API so that I can get the X-CSRF-TOKEN which needs to be set in the headers for the next time I make a post to the same API so I am able to get the .ROBLOSECURITY which is used to authenticate that the account session. However, the second time I post to their API with the token in the header, I get a 400 error and I am unsure of why this is occurring.
Also, for anyone who is wondering, it is returning a valid X-CSRF-TOKEN.
var request = require('request');
var loginOptions = {
url: 'https://auth.roblox.com/v2/login',
form: {
'ctype': 'Username',
'cvalue': 'AccountUsernameHere',
'password': 'AccountPassGoesHere'
},
headers: {
'Content-Type': 'application/json'
}
};
request.post(loginOptions, function(error, response, body) {
loginOptions.headers['X-CSRF-TOKEN'] = response.headers['x-csrf-token'];
request.post(loginOptions, function(error, response, body) {
if (response.statusCode == 200) {
console.log('Success: ' + body);
} else {
console.log(response.statusCode + ' : ' + response.statusMessage);
}
});
});
You need install cors in nodejs: npm install cors, you can try the following below
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
It appears there were two issues with my code.
The first issue is that I was using form when I should have been using body. I also ended up needing to add json: true too.

Resources