Send JSON data to another server (PayU) using express and angular - javascript

I am trying to make a payment application with PayU and don't know how can I send JSON data to PayU server. How I can do that?? Please help me or give me some advice. I should pass the information (from body: {...} below) POST to https://secure.snd.payu.com/api/v2_1/orders
Data which I should send to PayU (body: {...})
userFactory.paypalPayment = function(payment) {
return $http({
method: 'POST',
url: "/paynow",
headers: {
'Content-Type': 'application/json'
},
body: {
"notifyUrl": "https://your.eshop.com/notify",
"customerIp": "127.0.0.1",
"merchantPosId": "145227",
"description": "Toyota",
"currencyCode": "USD",
"totalAmount": "12",
"products":{
"name": "Wireless mouse",
"unitPrice": "15000",
"quantity": "1"
},
}
});
}
return userFactory
app.js (ExpressJS)
router.post('/paynow', function(req, res){
res.setHeader('Content-type', 'application/json; charset=utf-8');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.json({ success: true})
})
controller
app.payment = function(payment){
User.paypalPayment().then(function(data){
console.log(data.data)
if(data.data.success) {
$window.location = 'https://secure.snd.payu.com/api/v2_1/orders'
} else {
console.log('Wrong way')
}
})
}

In order to make HTTP request to another server from NodeJS application you can use request module (or request-promise-native if you prefer promises). Code might look like this:
router.post('/paynow', function(req, res){
// your code here
request({
method: 'POST',
json: { body: req.body },
uri: 'https://secure.snd.payu.com/api/v2_1/orders',
headers: { "Content-Type": "application/json" },
(err, response, body) => {
// Callback - you can check response.statusCode here or get body of the response.
// Now you can send response to user.
}
});
});

Related

I cannot view my JSON object in the console nor the terminal but I get a 200 status code

I am trying to get data points out of an API. I've used the authentication credentials and token to access and I get a status message 'ok' with a 200 code. I know I'm accessing but I cannot view the points nor stream any data in the terminal nor the console in the DOM.
1) I test this with Postman and I can get all the data in the terminal
method: 'GET',
url: 'https://www.url.io/rest/method/url-api/getDeviceData',
qs: { happy_token: 'eyJ0eXAiOiJKiOiJIUzI1NiJ9.ImlkfDM4ZDQ4OWM1LWI3YzUtNDE1Ni05ZWJlLWJmYzViMmJkODk1OXx0eXBlfHRpbWVzdGFtcHxpc0VuY3J5cHRlZHxvcmlnaW58MTAtMC0yOC0xODFfNTcwMDB8cG9saWN5fDHRsfGluYWN0aXZpdHlfdGhyZXNob2xkfDF8aXNUb2tlbnx1c2VybmFtZXxtb2hhbWVkLmZheWVkQHBkaWNvcnAuY29tfEd8NHwtMnw1fDZ8N3wkOHwkOXxIfEF8LTNdfEJ8JDl8SXxBfC0zXV18Q3wtMXxEfEVdIg.PaQdlILLK9lWN8zjmthTgWY_r77oBw' },
headers:
{
'cache-control': 'no-cache',
Connection: 'keep-alive',
'accept-encoding': 'gzip, deflate',
cookie: 'AWSALB=A+sdBzwAGrQmRer2y4ENHQgCc8TdDKiLHkM68CJMVKNhpVEBkiW53AhWSRKmzwk9scGKbSHeWtWL9YzuBayGFyWdkmkd5fkFSp2FYxbraW75UOoi8YtY',
Host: 'www.url.io',
'Postman-Token': '08e1668d-1f49-4451-a47e-61c9bae9df08,84944b9f-17eb-4520-88b2-344a7c46bdca',
'Cache-Control': 'no-cache',
Accept: '*/*',
'User-Agent': 'PostmanRuntime/7.13.0',
Authorization: 'Basic bW9oYW1lZC5ZEBwZGljb3JwLmNpAbWZheWVkMjk5OA=='
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
After I run npm start I get a beautifully JSON response:
"message": "Call successful",
"data": {
"device_id": {
"data": [
{
"parameters": {
"node_id": "1",
"ip_address": "172.00.00.00",
"tcp_id": "1"
},
"type": "P",
"mapping": "P",
"name": "P name",
"deviceName": "P name",
"path": "/profileView/devices/p name",
"deviceType": "P",
.
.
.
(etc)
This is what I want to get to!
However, when writing my code, as follows:
var credentials = function getCredentials() {
app.use(bodyParser.urlencoded({ extended: true }));
xhr.open("GET", URL, true, username, password);
xhr.withCredentials = true;
xhr.onreadystatechange = receiveResponse;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
xhr.open("POST", URL)
function receiveResponse(e) {
if (this.readyState == 4) {
if (this.status == 200) {
var response = this.responseXML
console.log(response);
}
}
}
}
function getToken(credentials) {
var data = response;
for (var i = 0; response[i]>1; I++) {
var results = response[i];
console.log(response[i]);
}
}
// server instance
const server = http.createServer((request, response) => {
response.end("hello azure");
console.log(response);
});
const port = process.env.PORT || 443;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
this is what I get in the terminal:
terminal response
Additionally, I can't see anything in the console log here:
Browser View
I feel like I am sending the right request but I cannot POST the data. Can anyone provide any insight? Thanks!

post with whatwg-fetch is working but no data being posted

Im having issues with a POST with "whatwg-fetch" the response is returnin as 200 but no data is passing.
this is the code on the server...
app.post('/promo', function(request, response) {
response.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
var promo = new PromoItem();
promo.imgUrl = request.body.imgUrl;
promo.name = request.body.name;
promo.description = request.body.description;
promo.category = request.body.category;
console.log('----------');
console.log(promo.name);
console.log(request.body.name);
console.log('----------');
promo.save(function(err, savedPromo) {
if (err) {
responde.status(500).send({
error: "Something happened, promo not saved !"
});
} else {
response.status(200).send("Success !");
}
});
});
both promo.name and request.body.name are returning as undefined.
The code on the client..
setPromo = () => {
const options = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
mode: 'no-cors',
body: JSON.stringify({
"imgUrl": "http://via.placeholder.com/900x200",
"name": "MI POST",
"description": "MI PRIMER POST",
"category": "Salud"
})
};
fetch('http://localhost:3010/promo', options).then(function(response) {
console.log('Status', response.status);
})
}
have manipulated the options with different values but still the same result.
any ideas?
thanks
It's possible that the data is not being parsed. In Express, POST bodies can be parsed by body-parser. There are usage examples on the Express website. Essentially, you can use the body-parser middleware like this:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
It can also be used on a per-route basis:
app.post('/promo', bodyParser.json(), function(request, response) { //...
If you are using a version of Express >= 4.16.0, bodyParser.json is available as express.json. (source)

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**
}

Axios won't send cookie, Ajax (xhrFields) does just fine

Using Axios
export function sendAll() {
return (dispatch) => {
dispatch(requestData());
return axios({
method: 'POST',
url: `${C.API_SERVER.BASEURL}/notification/sendAll`,
data: {prop: 'val'},
// responseType: 'json',
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
}).then((response) => {
dispatch(receiveData(response));
}).catch((response) => {
dispatch(receiveError(response));
// dispatch(pushState(null, '/error'));
})
}
};
Result using Axios
Using $.ajax
$.ajax({
url: " http://local.example.com:3001/api/notification/sendAll",
method: "post",
data: {},
crossDomain: true,
xhrFields: {
withCredentials: true
}
})
Result using $.ajax
I am unable to force Axios to send a POST when trying to attach data to POST (cookie doesnt get sent either way).
My server setup (express):
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", `${C.PROTOCOL}://${C.DOMAIN}:${C.PORT}`);
res.header("Access-Control-Request-Headers", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
I do not have a OPTIONS route defined. I want Axios to send POST with cookie.
router.post('/notification/sendAll', function (req, res, next) {
res.sendStatus(204);
// ...
});
I was facing a similar issue. Making a get/post request through Axios did not sent the same headers as a straight XHR request.
Then I just added the following just after the Axios require statement:
axios.defaults.withCredentials = true;
After that Axios started sending my cookie like the regular XHR request did.
Working example using Danielo515's answer:
import * as axios from 'axios';
axios.defaults.withCredentials = true;
export function getAll() {
const url = 'https://example.com';
return axios.get(url);
}

Github API error when creating repo from CL with node, JSON parsing error

Creating a node CLI to create repos from CL, having an issue posting to github api. I'm using the request module to post to the github API.
request.post({
url: 'https://api.github.com/user/repos',
headers:{
'User-Agent': 'git CL - node',
'Content-type': 'application/json'
},
auth:{
username: '-username-',
password: '-password-'
},
form:{
name: "a-new-repo"
}
}, function(err, res, body){
console.log(body);
});
The error I'm getting is {"message":"Problems parsing JSON","documentation_url":"http://developer.github.com/v3"}
I've tried a ton of things, like
Setting multipart data
body instead of form data
Setting the content-type
Sending as JSON
Things I know are correct
authentication --- I'm able to get a correct response if i do a GET req, its just the POST
POST path and headers
Link for request-module
Link for github-api
Set json to the data you want to send, not form:
request.post({
url: 'https://api.github.com/user/repos',
headers:{
'User-Agent': 'git CL - node',
'Content-type': 'application/json'
},
auth:{
username: '-username-',
password: '-password-'
},
json:{
name: "a-new-repo"
},
}, function(err, res, body){
console.log(body);
});
There is a parameter called json in the API docs, have you tried setting that to be true?
From my reading, this is what is necessary to send the form data as a JSON structure, rather than as form-encoded in the request body.
request.post({
url: 'https://api.github.com/user/repos',
headers:{
'User-Agent': 'git CL - node',
'Content-type': 'application/json'
},
auth:{
username: '-username-',
password: '-password-'
},
form:{
name: "a-new-repo"
},
json: true
}, function(err, res, body){
console.log(body);
});

Categories