Axios Post Request in NodeJS - node.js

I have an API call in POSTMAN, which I am trying to replicate in nodeJS project using Axios, but the result is not the same that of a POSTMAN.
The call looks like this in POSTMAN:
Inside the body element I have: models and values properties and Authorization is of type Bearer .
I get a response result as an array.
Now, I try to do the same using axios, but I get error:
Code
axios.defaults.baseURL = 'http://XXXXXXXXXXXXXXX:8069/api';
axios({
method: 'POST',
url: '/create/res.users',
data: {
models: 'res.users',
values: "{ 'login': 'john#gmail.com', 'name':'john', 'email':'john#gmail.com', 'password': '123123123' }"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + accessToken
},
})
.then(function (response) {
console.log("Register", response);
res.status(200).send({
message: response.data
});
})
.catch(function (error) {
console.log("Error", error.response.data);
res.status(error.response.status).send({
message: error.response.data
});
});
Error
{
"message": {
"name": "odoo.exceptions.RedirectWarning",
"message": "You cannot create a new user from here.\n To create new user please go to configuration panel.\n74\nGo to the configuration panel",
"arguments": [
"You cannot create a new user from here.\n To create new user please go to configuration panel.",
74,
"Go to the configuration panel"
],
"exception_type": "error",
"code": 500,
"description": "Restful API Error"
}
}

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, This document may help you:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

Related

ReCAPTCHA siteverify not returning JSON response

I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298

How to update a pull request by GitHub APP API?

I developed GitHub APP to manage pull requests process, I'm using two APIs
1. statuses check API
2. update-a-pull-request API
I get this error message when a request to update an existing pull request that was created by one of the users.
How I can get installation token with the right permissions?
{
"message": "Validation Failed",
"errors": [
{
"message": "Only the pull request author may change the maintainer_can_modify value",
"resource": "PullRequest",
"field": "maintainer_can_modify",
"code": "invalid"
}
],
"documentation_url": "https://developer.github.com/v3/pulls/#update-a-pull-request"
}
To execute API call, I need token, I generated the token in this way:
Created app in GitHub Account
Created a private PEM key in the APP
In code, created JWT token using PEM key
Using the JWT token to create installation token as below
Header
function generateJwtToken() {
return jsonwebtoken.sign(
{
iat: Math.floor(new Date() / 1000),
exp: Math.floor(new Date() / 1000) + 60,
iss: ISSUER_ID,
},
PEM,
{algorithm: 'RS256'},
);
}
let githubHeadersToAccessToken = {
'User-Agent': 'nodejs',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + generateJwtToken(),
'Accept': 'application/vnd.github.machine-man-preview+json'
};
Get Installation token
payloadToken = {
"repository_ids": [
],
"permissions": {
"pull_requests": "write",
"statuses": "write",
"administration" : "write",
"organization_administration": "write",
"contents": "write",
"team_discussions": "write",
}
};
request.get({
url: 'https://api.github.com/app/installations',
headers: githubHeadersToAccessToken
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('Connected App get token failed:', err);
}
console.log('APP Installation id');
console.log('Installation id: ' + JSON.parse(body)[0].id);
app_installed_id = JSON.parse(body)[0].id;
request.post({
url: 'https://api.github.com/app/installations/'+app_installed_id+'/access_tokens',
headers: githubHeadersToAccessToken,
json: payloadToken
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('Failed to get access token to GitHub: ', err);
}
//console.log(body);
console.log('Access token to GitHub: ' + body.token);
});
});
Update existind pull request that was created by one of the users
request.post({
url: 'https://api.github.com/repos/'+owner+'/'+repo+'/statuses/'+sha,
headers: githubHeadersApiV3,
json: {
"state": status,
"context": "PR <> GUS Validation"
}
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('Connected App get token failed:', err);
}
//console.log(body);
console.log('commit sha: ' + sha + ' updated with status: ' + status);
});
I want to update that the code is working, I can update pull request using Github APP.
The problem I mentioned happen when I try to change "maintainer_can_modify" in pull request, which is not allowed, only by owner, then I just removed it.
But in my case I wanted to add comment, change title, etc ..
I will leave this question as an example for building GitHub app to update pull request using NodeJS.

Discord Profil Picture Update from ElectronJS using request PATCH

I'm trying to code an application into Electron JS to allow the person to change their profile picture at the same time on several applications.
For this I use the APIs of each platform.
For Twitter it works correctly, but I block at the level of Discord.
I can make a GET request on the profile, but I can't do a : PATCH/users/#me
https://discordapp.com/developers/docs/resources/user#modify-current-user
I do not know if it's the token that does not offer enough power, because I only asked for Identity as permission on my application.
I tried to pass JSON between true and false,
to add a content type, but I still have the same answer: {code: 0, message: '401: Unauthorized'}
function postDiscord(image) {
const imageDataURI = require('image-data-uri')
let {token} = store.get('discordToken') //get stored token
imageDataURI.encodeFromFile(image)
.then(res => {
request({
method: 'PATCH',
url: 'https://discordapp.com/api/v6/users/#me',
headers: {
'Authorization': 'Bearer '+token,
'User-Agent': 'someBot (site, v0.1)'
},
body: {
'avatar': res
},
json: true
}, function(err, res) {
if(err) {
console.error(err);
} else {
console.log(res.body)
}
}
);
})
}
{code: 0, message: '401: Unauthorized'}
Refering to Discord :https://github.com/discordapp/discord-api-docs/issues/1057
Cannot upload new pics with Oauth :/

Request must have at least one newMediaItem - Google Photos API

I'm trying to create media item using Google Photos API. Endpoint is documented here. If I copy and paste my payload to an API explorer which can be found in documentation, I get success:
Request inputed to an API Explorer and Successful response.
If I do the same in my node js program, I'm getting an error.
This is what I do:
const accessToken = "MyAccessToken";
payload = {
"newMediaItems": [
{
"description": "picture",
"simpleMediaItem": {
"uploadToken": "CAIS+QIASsyg4OQLX2Ao5hy6I734/b01mjk3Mqpom6DQ24iv7ZfAYLiXAy0WpOXCWJBNHrmBs6FE+a9Axu5CML+Ryu4VGawyf4skxM763mzC5GcjMY4rS/r6IwOekBIoE/aMJLJpRr1gW8jdhVJM89+kioTx9d+shyYeQDbVI8ezb1lXGp6irc9hZl7QA6xd+msXzbLD5nb+wc5CA6du95tP3buh5R5N/Knn+NwByebdEPCusl+X3p7DZ6ha72kLthUqdvwFsp8dpnGbNQBq8AFPVNHXB4C543iq+dYiRFYtICCxO8xi2cpONVT54Jl6l9rGh3Vnidwj5IwkbsXkyiN96HfRb9XLh0rCBw4ydV6Y9+C+OmTAqlQwIKy50I/ykHyzggroeJSbgphiQwFR2EbHwAeSKdsdIB03ItnunHtf3F2LRIitDRGI1n4VUEYE1dYjrrjR791ao24Dp8J3Hg8IRb8E3vFTeYMWyOk4mh/zQGInfNBnRY2ruHH0JA"
}
}
]
};
const response = await fetch('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`
},
payload: JSON.stringify(payload)
});
const json = await response.json();
console.log(json);
And getting this response:
{ error:
{ code: 400,
message: 'Request must have at least one newMediaItem.',
status: 'INVALID_ARGUMENT' } }
What could go wrong here?
Any help is appreciated, thank you.
It looks like you are setting the JSON payload in the wrong parameter in your call to fetch. It should be set in the parameter body (and not in payload). The JSON itself looks okay.
This snippet should work:
const response = await fetch('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`
},
body: JSON.stringify(payload)
});
Source: node-fetch 'Post with JSON' example

error returned in postman to get access token but works in console for NodeJS

I am trying to access the token using authorization code after passing the authentication, it works in my console for nodejs using request-promise module however it doesnt work on postman it says
{
"error": "invalid_grant",
"error_description": "invalid authorization code"
}
however it works in the console for nodeJS
{"access_token":"eyJhbGciOiJIUzI1NiJ9.7DkDzFz89Y-W-HLlwnqA0YmA_mMrR8nZV44eC1gAJjEp2Zmq8SE9q0UmzXuU-hHuXseMNvpqQeRMhHeVTbn8J_ZCQmkkAgZ359CnKvnXe3mZoYAWM4oQbtJFefoa7mwsAEFKScyEaIqi1DqHTItVqZfbCYdzrbee88E2-pWteiE.CHAvVIanJrUlTZZ25LMUTzW7IO4qRGZ_B_wN7c5Kfkk","token_type":"Bearer","refresh_token":"uDhPe4dRJkUYB1rC9VuV","expires_in":2592000,"scope":"openid profile","id_token":"eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FjY2Vzcy5saW5lLm1lIiwic3ViIjoiVWU4NTUzNTBiNDIzYzI5ZjExYjIwZTgwZTJiZmE4MmQ1IiwiYXVkIjoiMTU1Njc5NDgxOCIsImV4cCI6MTUxNzkzMDc3MCwiaWF0IjoxNTE3OTI3MTcwLCJuYW1lIjoiSm9obiBCb3JqZSIsInBpY3R1cmUiOiJodHRwczovL3Byb2ZpbGUubGluZS1zY2RuLm5ldC8waG1URGV0bUpWTW50NUhCem5YUnhOTEVWWlBCWU9NalF6QVhJcVNBNGVQaDVSSzNRcFRINHVGQXdiUEI5V0pYTW9RWGgxR1Y5UGIwMVQifQ.mYUWJQ-YLrz4zEer5n1J-R3S1W37mDLx6g_mVmmWDTk"}
this is the code using nodeJS
var data = {
grant_type: "authorization_code",
code: qC,
redirect_uri: "https://sample.com/profile", //edited for security
client_id: 1, // edited for security
client_secret: "9" //edited for security
}
var options = {
method: 'POST',
url: 'https://api.line.me/oauth2/v2.1/token',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
// payload: 'grant_type=authorization_code&code="'+queryCode+'"&redirect_uri=https://line-poc-demo.herokuapp.com/profile&client_id=1556794818&client_secret=98760fb0cea2aebdf7848ecf93c19cf4',
form: data
}
//
rp(options)
.then(function (parsedBody) {
// POST succeeded...
console.log('bick dig' + parsedBody);
})
.catch(function (err) {
// POST failed...
console.log('err ' + err);
});
Is there something wrong with my code? Thank you, any help will be appreciated.

Resources