Posting form data using request module - Nodejs & Express - javascript

I'm using a platform for data security, and they have this code snippet showing how to post data to their platform:
They're using the request module: https://github.com/mikeal/request
const request = require('request');
request({
url: 'https://mypass.testproxy.com/post',
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({'secret' : 'secret_value'})
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log('Status:', response.statusCode);
console.log(JSON.parse(body));
}
});
It works fine, but I wanted to replace the 'secret' : 'secret_value' object with my form data, but I'm having a hard time figuring out how to do this.
The only way I know how to retrieve form data is with req.body:
function(req, res) {
var form = {
card_number: req.body.card_number,
card_cvv: req.body.cvv,
card_expirationDate: req.body.card_expirationDate,
};
// ...
});
How would I do that? Any help is greatly appreciated.
I know the code below is wrong, but that's the idea of what I want to achieve:
request( function(req, res) {
var form = {
card_number: req.body.card_number,
card_cvv: req.body.cvv,
card_expirationDate: req.body.card_expirationDate,
};{
url: 'https://mypass.testproxy.com/post',
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(form)
...```

The form data will be sent with the content type application/x-www-form-urlencoded e.g. card_number=123&cvv=456.
Express has a middleware to parse that https://expressjs.com/en/api.html#express.urlencoded
app.use(express.urlencoded());
The parsed values will be in req.body in your post route. So e.g. req.body.card_number will contain the value 123.
You can put the request inside the route:
app.post('/', function (req, res) {
var form = { /* ... */ }
request({
body: JSON.stringify(form),
/* ... */
})
})

Related

When I post data with fetch post, I don't receive data

I have a problem with fetch post, I want to send data to an url but it doesn't work..
function TodoTaskForm () {
const taskContentInput = useRef(null)
const handleSubmit = async (e) => {
e.preventDefault()
fetch('/api/tasks', {
method: 'POST',
body: JSON.stringify({content: taskContentInput.current.value})
})
}
return (
<form onSubmit={handleSubmit} className="__component_todolist_form_container">
<input type="text" name="task" ref={taskContentInput} placeholder="nouvelle tâche.."></input>
</form>
)
}
In my component, I'm doing this and in my express server :
app.post('/api/tasks', (req, res) => {
console.log(req.body)
console.log('request received!')
})
When I test, i receive the request but req.body return "{}" in my console, I don't understand, im using app.use(express.json()) but it doesn't work, I have even try to use body-parser but...
So please, I need help.. thank you!
You need:
A body parser which matches the data being send. You've switched from sending form encoded data to sending JSON. Note that Express has built-in body parsing middleware and does not need the separate body-parse NPM module.
A Content-Type header on the request which states what format the data is in so the correct body parser can be triggered.
Such:
app.post('/api/tasks', express.json(), (req, res) => {
console.log(req.body)
console.log('request received!')
})
and
fetch('/api/tasks', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({content: taskContentInput.current.value})
})

Invalid request, some parameters are invalid or missing using express and node

I am struggling to get the access token of the user on LINE oauth2, everything works fine as I can redirect the user to callback URL and generate code in the URL, I've also managed to work it in POSTMAN but in my code, it throws an error
"Invalid request, some parameters are invalid or missing".
Any help is appreciated. Thank you.
Here is my code.
var queryCode;
app.get("/profile", function (req, res, next) {
console.log('Request Type:', req.query.code);
queryCode = req.query.code;
console.log(typeof queryCode);
res.render('pages/profile', { code: req.query.code });
var data = {
grant_type: "authorization_code",
code: queryCode,
redirect_uri: "https://mydemosampleonlywebsite.com/profile", // not real edited
client_id: 2, // edited for security
client_secret: "98" // edited for security
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('body ' + body);
}else{
console.log('err ' + body);
}
}
var options = {
method: 'POST',
url: 'https://api.line.me/oauth2/v2.1/token',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify(data)
}
request.post(options, callback);
res.end();
});
I've managed to solved it using form property instead of body in my options object.
var options = {
method: 'POST',
url: 'https://api.line.me/oauth2/v2.1/token',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
**form: data**
}

POST method through node.js

I am writing a simple node.js for a REST API call to create object through POST method and get the response code. But while running the script I get "0 passing" .
Here is my code:
var request = require("request");
var options = { method: 'POST',
url: 'https://example.org',
headers:
{ 'content-type': 'application/vnd.nativ.mio.v1+json',
authorization: 'Basic hashedTokenHere' },
//body: '{\n\n"name": "My JS TEST",\n"type": "media-asset"\n\n}'
};
request(options, function (error, response, body) {
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
Can anyone help to to run it successfully and get the response code?
Thanks!
I calling my local API hope this will make thing get clear. It's work for me
This my API
var express = require('express')
var router = express.Router()
var bodyParser = require('body-parser');
var app=express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/api',function(req,res)
{
res.status(200).send(req.body.name+"hi");
})
app.listen(8080,function(){
console.log("start");
})
Now, through Request, i will request this post method
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-type': 'application/json',
'Authorization': 'Basic ' + auth,
}
var postData = {
name: 'test',
value: 'test'
}
// Configure the request
var options = {
url: 'http://127.0.0.1:8080/api',
method: 'POST',
json: true,
headers: headers,
body: postData
}
// Start the request
request(options, function (error, response, body) {
// Print out the response body and head
console.log("body = "+body+" head= "+response.statusCode)
}
})

How to pass json to nodejs request post method?

I try to pass json to nodejs post method.But i'm getting error "The search query must be specified.". I have specified search string and filter the code. Can you advise what cause this error.
Same request working in POSTMAN.
//Load the request module
var express = require('express');
var request = require('request');
var app = express();
//Lets configure and request
request({
url: 'http://host:8080/rest/1.0/search',
qs: {query: 'nodejs*'},
method: 'POST',
json: {
filter:
{
community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
type: {asset:['00000000-0000-0000-0000-000000011001']},
},
fields: ['name']
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
app.listen(8080);
As per your postman screenshot you can try the below code by getting rid of qs: {query: 'nodejs*'} and adding the same inside the json.
//Load the request module
var express = require('express');
var request = require('request');
var app = express();
//Lets configure and request
request({
url: 'http://host:8080/rest/1.0/search',
method: 'POST',
json: {
query: 'nodejs*',
filter:
{
community: ['33862a97-44e5-4de5-9206-db0a61dd83ca'],
vocabulary: ['b80f3576-0642-4049-bb07-d72a0dd9e3e0','48029bb8-0585-4ed5-afaa-55014aebfcb3'],
type: {asset:['00000000-0000-0000-0000-000000011001']},
},
fields: ['name']
}
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
app.listen(8080);

how can I use data from the frontend to make a http request on my server

I have a http request in node:
var options = {
method: 'POST'
, url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
, qs:
{ location: '44.019076299999995, -123.10060789999999',
type: 'restaurant',
opennow: 'true',
rankby: 'distance',
key: 'my key' }
, headers: {
'cache-control': 'no-cache'
, 'content-type': 'application/json'
}
, json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {data : body.results});
});
});
But I am stuck on how I can can get data from the user on the front end to use in my request. for example I am getting the users coordinates using geolocation on the front end. how can I plug this into my request? what about if the user wanted to add a search parameter? I know I can have my user make the request on the front end with ajax, but that leaves me with the problem of having my api key exposed on the front end. What is the pattern to solve this problem?

Categories