I write a test which firstly has to do post request. I get an error when I run this :
the url is :
http://walla.com:8080/internal/getToken
the code :
function user(){
var postData = {
loginName: 'hello#gmail.com',
password: 'abcdef'
}
var options = {
host: 'http://walla.com',
port: '8080',
path: '/internal/getToken',
body: postData
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
var callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.end();
}
describe("ccc", function () {
it("bbbb" , function(){
user();
});
});
Am i doing something wrong?
thanks?
You are missing a comma after the body
var options = {
host: 'http://walla.com',
port: '8080',
path: '/internal/getToken',
body: postData, // Note the Comma at the end
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
Instead, you can directly define the object, like this
var options = {
host: 'http://walla.com',
port: '8080',
path: '/internal/getToken',
body: {
loginName: 'hello#gmail.com',
password: 'abcdef'
},
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
Related
I have some code that looks like this in Next JS
const resApp = await fetch('/api/club/createsignalapp', {
body: JSON.stringify({
name: event.target.name.value,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
})
const appResult = await resApp.json()
--createsignalapp
export default async (req, res) => {
var mydata
var createApp = function (data) {
var headers = {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Basic APIKKEY`,
}
var options = {
host: 'onesignal.com',
port: 443,
path: '/api/v1/apps',
method: 'POST',
headers: headers,
}
var https = require('https')
var myreq = https.request(options, function (myres) {
myres.on('data', function (data) {
mydata = JSON.parse(data)
res.statusCode = 200
res.json({
response: {
boolean: true,
alert: '',
message: '',
},
data: mydata
})
})
})
myreq.on('error', function (e) {
console.log(e)
})
myreq.write(JSON.stringify(data))
myreq.end()
}
var message = {
name: req.body.name
}
createApp(message)
}
This hits the error API resolved without sending a response for /api/club/createsignalapp, this may result in stalled requests.
I'm not sure how to do this correctly as i'm getting confused with the awaits and asyncs and requests everywhere.
Happy to hear suggestions.
Thanks
I'm trying to add body data into post request in Electron.js. But data writes in some other property. How to properly write data in request?
function tokenRequest() {
var postData = JSON.stringify({
username: USERNAME,
password: PASSWORD,
});
const tokenRequest = net.request({
method: 'POST',
protocol: 'https:',
hostname: HOST,
port: PORT,
path: '/api2/json/access/ticket',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
});
tokenRequest.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
response.on('end', () => {
console.log('No more data in tokenRequest response.');
});
});
tokenRequest.write(postData);
tokenRequest.end();
}
Console output:
Since Proxmox is only accepting URL-encoded JSON data (source) you have to replace your JSON.stringify() with new URLSearchParams(). Also add toString() to postData before writing it. Here is the full code:
function tokenRequest() {
const postData = new URLSearchParams({ // <----
username: USERNAME,
password: PASSWORD,
})
const tokenRequest = net.request({
method: 'POST',
protocol: 'https:',
hostname: HOST,
port: PORT,
path: '/api2/json/access/ticket',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
tokenRequest.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => console.log(`BODY: ${chunk}`))
response.on('end', () => console.log('No more data in tokenRequest response.'))
})
tokenRequest.write(postData.toString()) // <----
tokenRequest.end()
}
The following is my code:
async function asynccall() {
//POST request (create order)
var data = JSON.stringify({
merchant_urls: {
terms: "https://www.example.com/terms.html",
checkout: "https://atelierdecosmetique.herokuapp.com/checkout",
confirmation: "https://atelierdecosmetique.herokuapp.com/confirmation",
push: "https://www.example.com/api/push",
},
});
var config = {
method: "post",
url: "https://api.playground.klarna.com/checkout/v3/orders/",
headers: {
"Content-Type": "application/json",
Authorization: "",
},
data: data,
};
var orderid = Postrequest.data.order_id;
//GET Request (read order)
var axios = require("axios");
var data1 = JSON.stringify({
merchant_urls: {
confirmation: "https://www.example.com/confirmation.html" + Postrequest.data.order_id,
},
});
var config1 = {
method: "get",
url: "https://api.playground.klarna.com/checkout/v3/orders/",
headers: {
"Content-Type": "application/json",
Authorization:
},
data: data1,
};
//The calls as variables
var Postrequest = await axios(config);
var Getrequest = await axios(config1);
console.log(Getrequest.data.merchant_urls.confirmation)
app.get("/checkout", function(req, res) {
res.render("checkout.ejs", {
datapost: Postrequest.data.html_snippet
})
});
app.get("/confirmation", function(req, res) {
res.render("confirmation.ejs", {
dataget: Getrequest.data.html_snippet
});
});
}
asynccall();
My problem with this code is that the Postrequest.data.order_id is not shown in the GET request's merchant_urls.confirmation URL when I console log it at the end of the code. It should return the confirmation page URL with the order_id response from the POST request at the end. How could I solve this? I know it has to do with asynchronous and synchronous code? I'm stuck and really need this to work.
You need to get the results of the first request before using the returned data in the second.
async function asynccall() {
var axios = require("axios");
//POST request (create order)
var data = JSON.stringify({
merchant_urls: {
terms: "https://www.example.com/terms.html",
checkout: "https://atelierdecosmetique.herokuapp.com/checkout",
confirmation: "https://atelierdecosmetique.herokuapp.com/confirmation",
push: "https://www.example.com/api/push",
},
});
var config = {
method: "post",
url: "https://api.playground.klarna.com/checkout/v3/orders/",
headers: {
"Content-Type": "application/json",
Authorization: "",
},
data: data,
};
var Postrequest = await axios(config);
var orderid = Postrequest.data.order_id;
//GET Request (read order)
var data1 = JSON.stringify({
merchant_urls: {
confirmation: "https://www.example.com/confirmation.html" + Postrequest.data.order_id,
},
});
var config1 = {
method: "get",
url: "https://api.playground.klarna.com/checkout/v3/orders/",
headers: {
"Content-Type": "application/json",
Authorization: ""
},
data: data1,
};
//The calls as variables
var Getrequest = await axios(config1);
console.log(Getrequest.data.merchant_urls.confirmation)
app.get("/checkout", function(req, res) {
res.render("checkout.ejs", {
datapost: Postrequest.data.html_snippet
})
});
app.get("/confirmation", function(req, res) {
res.render("confirmation.ejs", {
dataget: Getrequest.data.html_snippet
});
});
}
asynccall();
Here is the rest client in our service:
self.headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
};
self.loginClient = $resource(self.baseUrl + '/users/login', {
userId: '#userId',
password: '#password'
}, {
save: {
method: 'POST',
headers: self.headers
}
});
I call it like this -
AuthService.loginClient.save({
userId: self.user.email,
password: self.user.password
}).$promise.then(function (res) {
// do stuff
})
The URL path that the browser is hitting looks like this:
/users/login?password=XXXXXX&rememberMe=false&userId=XXXXXX
Can anyone tell what I have wrong here that is leading to the url encoding of my POST params? Please let me know what other info I can provide.
Just pass the data to the action method.change the service like this
self.headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
};
self.loginClient = $resource(self.baseUrl + '/users/login', {
save: {
method: 'POST',
headers: self.headers
}
});
call it like this
AuthService.loginClient.save({},{
userId: self.user.email,
password: self.user.password
})
I'm trying to connect to a remote server using nodejs 0.12, and i keep getting the response SELF_SIGNED_CERT_IN_CHAIN. I have looked at similar questions 1 2 but somehow their solutions don't work on my server.
I am connecting to a test environment outside of my control setted up with a self signed certificate. This is my request:
var https = require("https");
var fs = require('fs');
start();
function start()
{
var listadebancos =
{
language:"es",
command:"GET_BANKS_LIST",
merchant:
{
apiLogin:"111111111111111",
apiKey:"11111111111111111111111111",
},
test:true,
bankListInformation:
{
paymentMethod:"PSE",
paymentCountry:"CO"
}
};
var listadebancosString = JSON.stringify(listadebancos);
var headers =
{
'Content-Type': 'application/json',
'Content-Length': listadebancosString.length
};
var options= {
host: 'stg.api.payulatam.com',
rejectUnauthorized: false,
agent:false,
path: '/payments-api/4.0/service.cgi',
method: 'POST',
cert: fs.readFileSync('./stg.gateway.payulatam.crt'),
}
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var req= https.request(options, funcionRespuesta);
req.write(listadebancosString);
req.end();
function funcionRespuesta(res)
{ console.log(res);
}
}
Am i missing something obvious?
I decided to use a library call needle to make the request and this time i was able to receive the response with no SSL errors. Just in case anyone is in the same situation here is the code i used:
var listadebancos =
{
"language":"es",
"command":"GET_BANKS_LIST",
"merchant":{
"apiLogin:"111111111111111",
"apiKey:"11111111111111111111111111",
},
"test":false,
"bankListInformation":{
"paymentMethod":"PSE",
"paymentCountry":"CO"
}
};
};
// var listadebancosString = JSON.stringify(listadebancos);
var headers =
{
'Content-Type': 'application/json'
};
var options = {
host: 'stg.api.payulatam.com',
**json:true,**
path: '/payments-api/4.0/service.cgi',
method: 'GET',
headers: headers,
rejectUnauthorized: false,
requestCert: true,
agent: false,
strictSSL: false,
}
needle
.post('stg.api.payulatam.com/payments-api/4.0/service.cgi',listadebancos, options, funcionRespuesta)
.on('end', function() {
console.log('Ready-o, friend-o.');
})
function funcionRespuesta(err, resp, body)
{
console.log(err);
console.log(body);
}