I want to make an HTTP POST request to a server with credentials (username, password) and content.
More specifically, I used various approaches without success. One of them is:
var request = require('request');
request({
url: 'https://path',
method: 'POST',
auth: {
user: 'username',
pass: 'password'
},
form: {
'grant_type': 'client_credentials',
'text' : 'input-text',
'features': {
'score': true,
}
}
}, function(err, res) {
console.log(res);
var json = JSON.parse(res.body);
console.log("Access Token:", json.access_token);
});
Do you have any suggestion?
I feel more comfortable using promises. request-promise documentation
var request = require('request-promise');
var options = {
method: 'POST',
url: '',
auth: {
user: '',
password: ''
},
headers: {
'': ''
},
json: true
}
return request(options)
.then(function (response) {
// manipulate response
}).catch(function (err) {
return err
})
Related
I'm working on a web app and I'm sending a post request with ajax to a node+express backend. The problem is that in the backend the values for all parameters are NULL, I have checked by console.log(data) on the front end before sending ajax request and I'm getting the values here but on the backend request.query has all params with NULL values.
AJAX Request
const data = {
first_name: fn,
last_name: ln,
email: email,
password: password,
job_title: job,
security: security,
mobile: mobile,
remarks: remarks,
};
console.log("Data : ");
console.log(data);
$.post(
"http://127.0.0.1:4000/user/add",
data,
function (response) {
console.log(response);
}
);
Console Log For Data
Data :
{first_name: 'a', last_name: 'a', email: 'admin#gmail.com', password: '13011301', job_title: 'CV-Specialist', …}
Backend Code
app.post("/user/add", (req, res) => {
const data = req.query;
var sql =
"Insert into users (first_name,last_name,email,password,job,security,mobile,remarks) values (?,?,?,?,?,?,?,?)";
conn.query(
sql,
[
data.first_name,
data.last_name,
data.email,
data.password,
data.job,
data.security,
data.mobile,
data.remarks,
],
function (err, result) {
if (err) {
res.send(err);
} else {
res.send("1 record inserted");
}
}
);
});
Backend Response
{code: 'ER_BAD_NULL_ERROR', errno: 1048, sqlMessage: "Column 'first_name' cannot be null", sqlState: '23000', index: 0, …}
code
:
"ER_BAD_NULL_ERROR"
errno
:
1048
index
:
0
sql
:
"Insert into users (first_name,last_name,email,password,job,security,mobile,remarks) values (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)"
sqlMessage
:
"Column 'first_name' cannot be null"
I have searched for solutions and explanations but I can't figure out what's causing this. Any help or hints will be appreciated, thank!
The default content type header of jquery for Ajax is application/x-www-form-urlencoded. You are expected to send data in the query Params like so:
$.ajax({
url: 'http://www.example.com?' + $.param({first_name: 'a', last_name: 'a', email: 'admin#gmail.com', password: '13011301', job_title: 'CV-Specialist', …}),
method: 'POST'
});
Either send all of your data encoded in query params as shown above
or
set headers to application/json
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Content-Type':'application/json'
},
method: 'POST',
data: data,
success: function(data){
console.log('succes: '+data);
}
});
on the server side ensure you have body parser configured:
const bodyParser = require('body-parser');
.
.
.
.
.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
In your middleware callback get data in req.body instead of req.query :
app.post("/user/add", (req, res) => {
const data = req.body;
var sql =
"Insert into users (first_name,last_name,email,password,job,security,mobile,remarks) values (?,?,?,?,?,?,?,?)";
conn.query(
sql,
[
data.first_name,
data.last_name,
data.email,
data.password,
data.job,
data.security,
data.mobile,
data.remarks,
],
function (err, result) {
if (err) {
res.send(err);
} else {
res.send("1 record inserted");
}
}
);
});
Task
Parse a CSV file
Send the data to an API enpoint
Save data to MySql database
Problem
The request body is showing up empty when I send data via fetch. However, I can send and see the body data if I use Postman.
I've added a console.log(req.body) and it's printing out {} to the console.
Parse and Send Data to Endpoint
const changeHandler = (event) => {
Papa.parse(event.target.files[0], {
header: true,
skipEmptyLines: true,
complete: function (results) {
results.data.forEach(entry => {
// Create the data object.
let data = {};
let keys = ['Date', 'Description', 'Debit Amount'];
for (let key in entry) {
if (keys.includes(key)) {
data[key.toLowerCase().replaceAll(' ', '_')] = entry[key];
}
}
// Send data to server
fetch('http://localhost:3001/api/create_transactions', {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}).then(function (response) {
console.log(response);
})
});
},
});
// Reset file input
event.target.value = null;
};
Save Data to MySql
app.use(express.json());
const crypto = require('crypto');
app.post("/api/create_transactions", (req, res) => {
console.log(req.body);
/*
let hash = crypto.createHash('md5').update(req.body['date'] + req.body['description'] + req.body['debit_amount']).digest('hex');
let data = [
hash,
req.body['date'],
req.body['description'],
req.body['debit_amount'],
];
db.query('insert into transactions (`hash`, `date`, `description`, `debit_amount`) values (?, ?, ?, ?)', data, (err, result, fields) => {
if (err) {
console.log(err);
} else {
console.log(result);
res.send(JSON.stringify({"status": 200, "error": null, "response": result}))
}
});
*/
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
According to this post Fetch: post json data, application/json change to text/plain you can not change the Content-Type to application/json if you are using no-cors. So I will have to enable cors if I want to use fetch.
Using this tutorial https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/ I was able to enable cors on my nodejs server and receive the proper headers.
Try to use express's bodyParser app.use(express.bodyParser());
I'm trying to make my application sending a post request and receiving a response using Axios. However i encoutered errors while trying to make a post request.
My code for making post request:
onPostJson = () => {
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi',
{
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
})
.then((response) => {
console.log(response.json());
}, (error) => {
console.log(error);
});
};
Error:
Network Error
- node_modules\axios\lib\core\createError.js:15:17 in createError
- node_modules\axios\lib\adapters\xhr.js:80:22 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
I suspected that there is problem with the URL, but i successfully made a post request to this URL using Postman.
Solution: It was syntax error. I forgot to include Header configurations in the code.
onPostJson = () => {
console.log("onpost");
axios.post('http://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
FromDate: "01-Jan-2020",
ToDate: "01-May-2020",
}, {
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImtpZW50ZC5haXRzIiwibmJmIjoxNTkzNzY0MDU0LCJleHAiOjE1OTQzNjg4NTQsImlhdCI6MTU5Mzc2NDA1NH0.liIM6g2E_EMXvnRpL1RcU-QVyUAKYxVLZZK05OqZ8Ck',
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then(respond => {
// console.log(respond.data.CaThuHoiList);
setShiftData(respond.data.CaThuHoiList);
})
.catch(function (error) {
console.log('Error');
console.log(error);
});
}
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
});
i'm not sure, but ..
Do you want to try it like the code above?
Via the code following I get this error:
error: Error: [mobx-state-tree] Cannot modify
'AuthenticationStore#<root>', the object is protected and can only be
modified by using an action.
the code (generator) in question:
.model('AuthenticationStore', {
user: types.frozen(),
loading: types.optional(types.boolean, false),
error: types.frozen()
})
.actions(self => ({
submitLogin: flow(function * (email, password) {
self.error = undefined
self.loading = true
self.user = yield fetch('/api/sign_in', {
method: 'post',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'user' : {
'email': email,
'password': password
}
})
}).then(res => {
return res.json()
}).then(response => {
self.loading = false // the error happens here!
return response.data
}).catch(error => {
console.error('error:', error)
// self.error = error
})
}), ...
The question: is this not permitted in a generator, is there a better way to update this particular state or does it need to be wrapped by a try/catch?
As always thanks is advance for any and all feedback!
The problem is you're calling then on the Promise returned by fetch(), and the function you pass to then is not an action. Note that functions that run within an action (or flow) do not count as the action itself.
Since you're using yield, you don't need to call then or catch on the Promise returned by fetch(). Instead, wrap it in a try/catch:
submitLogin: flow(function* (email, password) {
self.error = undefined;
self.loading = true;
try {
const res = yield fetch('/api/sign_in', {
method: 'post',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'user' : {
'email': email,
'password': password
}
})
});
const response = yield res.json();
self.loading = false;
self.user = response;
} catch(error) {
console.log('error: ', error);
self.error = error;
}
}
we have storage array which supports REST API. I am able to do all ( GET/POST/DELETE/PUT) through postman and need to implement one of POST operation through Node.js script.
I am successful in node.js GET operation. But still not able to get the simple POST operation through multiple tries with various forms. here is the codes of both GET and PUT. Also the successful POST operation screenshot by the postman.
Appreciate any help.
GET: Node.js code ( working ):
var request = require('request');
function get_trustyou(trust_you_id, callback){
var options = {
url: 'https://xxxxxx/api/json/v2/types/consistency-groups',
rejectUnauthorized: false,
method: 'GET',
type: 'application/json',
auth:{
user: 'xxxxx',
pass: 'xxx'
}
};
var res = '';
request(options, function ( error, resp, body ) {
if ( !error && resp.statusCode == 200){
res = body;
}
if (error) {
console.log("this is error" + error);
}
callback(res);
});
}
get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
console.log("Here is the result" + resp);
});
POST: Node.js code ( Not working ):
var request = require('request');
function get_trustyou(trust_you_id, callback){
var options = {
body: postData,
url: 'https://xxxx/api/json/v2/types/consistency-groups',
rejectUnauthorized: false,
method: 'POST',
type: 'application/json',
auth:{
user: 'xxxx',
pass: 'xxxxx'
},
form: {
'consistency-group-name': 'TEST-CG'
}
};
request(options, function ( error, resp, body ) {
if ( !error && resp.statusCode == 200){
res = body;
}
if (error) {
console.log("this is error" + error);
}
callback(res);
});
}
get_trustyou("674fa44c-1fbd-4275-aa72-a20f262372cd", function(resp){
console.log("this is the responce" + resp);
});