I am trying to make POST request for OTP using Node.Js Express. Below is the code for making post request using request but I want to make post request using Express.
const request = require('request');
const options = {
method: 'POST',
url: 'https://d7-verify.p.rapidapi.com/send',
headers: {
'content-type': 'application/json',
authorization: 'undefined',
'x-rapidapi-key': 'e47df3d7e5msh868bdee0049d425p19',
'x-rapidapi-host': 'd7-verify.p.rapidapi.com',
useQueryString: true
},
body: {
expiry: 900,
message: 'Your otp code is {code}',
mobile: 971562316353,
sender_id: 'SMSInfo'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
How can I make above request in Express framework?
Express, is a back end web application framework for Node.js. To receive such requests using Express.js the following code will be helpful
var express = require('express')
var app = express()
// POST method route
app.post('/sendotp', function (req, res) {
//Generate OTP
var otp=Math.floor(100000 + Math.random() * 900000);
//Get Mobile number from response body
var mobile=req.body.mobile;
//Then send OTP to respective mobile number
// send sucess message to use
res.send('OTP Sent Successfully')
})
Related
I'm building MEAN stack app, so I have at backend node+express server, Angular on front.
Atm I need to reach a remote non-cors server with data by sending a POST request to it. Googled for a day, and understand that I need to establish a proxy middleware. Trying to use this on backend server:
app.use(
"/getPrice",
createProxyMiddleware({
target: someurl,
changeOrigin: true,
logLevel: "debug",
onProxyReq(proxyReq, req, res) {
proxyReq.setHeader("X-DV-Auth-Token", sometoken);
proxyReq.setHeader("Access-Control-Allow-Origin", "*");
proxyReq.setHeader("Content-Type", "application/json");
req.body = JSON.stringify(req.body);
},
})
);
But request didn't return anything.
On other hand trying same url, payload and headers from PostMan, I have response with data exactly I need.
But PostMan offers only request-based solution which I can't adopt for using with express and http-proxy middleware
var request = require('request');
var options = {
'method': 'POST',
'url': someurl,
'headers': {
'X-DV-Auth-Token': sometoken,
'Content-Type': 'application/json',
'Cookie': somecookie
},
body: JSON.stringify({requestBodyObject})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Please, point me, where I probably missing a bit, or suggest how to adopt PostMan's code into express & http-proxy solution.
Thanks in advance
Appending req.body in http-proxy should be done using proxyReq.write(JSON.stringify(body)).
So the modified createProxyMiddleware function would be:
app.use(
"/getPrice",
createProxyMiddleware({
target: someurl,
changeOrigin: true,
logLevel: "debug",
onProxyReq(proxyReq, req, res) {
proxyReq.setHeader("X-DV-Auth-Token", sometoken);
proxyReq.setHeader("Access-Control-Allow-Origin", "*");
proxyReq.setHeader("Content-Type", "application/json");
console.log(req.body);
if (req.body) {
let bodyData = JSON.stringify(req.body);
// stream the content
proxyReq.write(bodyData);
}
},
})
);
Also, before you try the above changes, please make sure if you are receiving data in req.body or not.
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...`);
});
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
})
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.
I'm using a combination of Express and Request (installed using npm) to try to send a get request to get some json from the server. However no matter what I do the body that is returned is "undefined".
This is the code in my server.js file. The json isn't actually what I'm sending, it's just an example as I can't post what I'm actually sending.
import express = require("express");
import bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
})
app.listen(3000);
I've tried both of the following but both of them say that body is undefined.
import request = require("request");
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
this.config = JSON.parse(body);
})
request(`/config`, function(err, res, body) {
this.config = JSON.parse(body);
});
Does anyone know what I'm doing wrong? I've never used express or request before so any tips would be greatly appreciated.
UPDATE
If I change the request code to the following, the inside of the function is never run. Does anyone know why this would be?
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
console.log("response => "+JSON.parse(body));
return JSON.parse(body);
})
Since OP hasn't got it working and I believe the code he got up there is correct. I may as well post my working solution here to help him get started.
Hopefully this will save you hours of debugging...
Client:
"use strict";
let request = require("request");
let req = {
url: `localhost:4444/config`,
proxy: 'http://localhost:4444',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
request(req, function (err, res, body) {
this.config = JSON.parse(body);
console.log("response => " + this.config);
});
Server:
"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
});
// Start the server
app.set('port', 4444);
app.listen(app.get('port'), "0.0.0.0", function() {
console.log('started');
});
Output:
response => {name: test}
I dont't know if you have posted whole of your server's code, it seems like you missed app.listen(port) so that your server cannot be started up correctly.
Also, if you added if (error) { console.log(error); } at the first line of the callback function of request, you'll find it print an error: [Error: Invalid URI "/config"]
And that's why the body is always undefined: You have to give the full url such like http://localhost:xxxx to request.
In short:
Your server didn't listen to a specific port. app.listen(5678)
Your client didn't know the complete url. request('http://localhost:5678/config', (...)=>{...})