im trying to ensure some user and get in post 500 (Internal Server Error).
function ensureUser(webUrl,loginName)
{
var data = { 'logonName': loginName };
return $.ajax({
url: webUrl + "/_api/web/siteusers",
type: "POST",
data: JSON.stringify(data),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose"
}
});
}
var loginName = 'i:0#.w|nsm\eilonte'
ensureUser(_spPageContextInfo.webAbsoluteUrl,loginName)
.done(function(data)
{
console.log('success');
})
.fail(function(error){
console.log(error);
});
this is the error:
jquery-1.12.4.js:10254 POST http://blabla/_api/web/ensureuser 500 (Internal Server Error)
send # jquery-1.12.4.js:10254
ajax # jquery-1.12.4.js:9738
ensureUser # VM2574:4
(anonymous) # VM2574:17
cant identify what is the problem.
Try using below code for ensure user.
function ensureUser(webUrl,loginName)
{
var payload = { 'logonName': loginName };
return $.ajax({
url: webUrl + "/_api/web/ensureuser",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(payload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose"
}
});
}
var loginName = 'emailid'
ensureUser(_spPageContextInfo.webAbsoluteUrl,loginName)
.done(function(data)
{
console.log('User has been added');
})
.fail(function(error){
console.log('An error occured while adding user');
});
You are not sending the username as JSON. Change the "Content-Type" header to:
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
Also I think the API endpoint is
_api/web/ensureuser
Related
I am using the request promise plugin request to create the get and post api. I want to pass the URL with a parameter. below is my code. How to pass parameter value in URL?
async function getDetails (req) {
var options = {
url: 'http://localhost:3000/api/student/id/{studen_id}/branch/{studentbranch}',
method: 'GET',
headers: {
'User-Agent': 'my request',
'Authorization': 'Bearer {my token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
},
json: true
};
let res= await rp(options)
.then(function (body) {
return body;
})
.catch(function (err) {
console.log("error get balance",err)
});
return res;
}
To pass the parameter by URL, you can pass like this:
http://localhost:3000/api/student/?id={studen_id}&branch={studentbranch}
async function getDetails (req) {
var options = {
url: 'http://localhost:3000/api/student/id/'+encodeURIComponent(req.body.id)+'/branch/'+encodeURIComponent(req.body.branch),
method: 'GET',
headers: {
'User-Agent': 'my request',
'Authorization': 'Bearer {my token}',
'Content-Type': 'application/json',
'Accept': 'application/json'
},
json: true
};
let res= await rp(options)
.then(function (body) {
return body;
})
.catch(function (err) {
console.log("error get balance",err)
});
return res;
}
I'm trying to get an authorization token by making a request to an api using axios:
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
auth: {
username: usr,
password: pwd
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})
I'm getting always status code 401(Unauthorized):
Error: Request failed with status code 401
Where I'm doing wrong?
The fact is that making the same request using python works fine:
payload = "username=%s&password=%s" % (usr,pwd)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url_login, data=payload, headers=headers)
print(response.text)
data = response.json()
token = data["token"]
By sending username and password in auth: {} in axios, you are doing the basic-authentication, basically sending Authorization: basic <base64(user:pass)> header.
As per working python program, you need to send the username and password as part of the request body. You need to serialize the body params for url-encoded content type as well.
e.g.
const querystring = require('querystring');
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: querystring.stringify({
username: usr,
password: pwd
})
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})
How can we use bearer token with POST method using npm sync-request? The sync-request resource page has the way to use authorization in GET request but not in POST request.
*******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent'
}
});
****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
json: { username: 'Name' }
});
Not sure why you would want to use sync-request which can cause timing issues but this should work with either sync-request or request
// *******GET Request*******
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
'headers': {
'user-agent': 'example-user-agent',
'authorization', 'Bearer ' + authId
}
});
// ****POST Request*****
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
'headers': {
'authorization', 'Bearer ' + authId
},
json: { username: 'Name' }
});
authId needs to be whatever your bearer token spoils be for your app.
I would suggest use of axis and example below:-
GET
import axios from "axios";
axios({
method: 'get',
url: url,
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}).catch((err) => {
console.log(err)
));
POST
axios({
method: 'post',
url: url,
data: JSON.stringify({orders}),
headers: {
'Content-Type': 'application/json',
'Authorization': userObj.token
}
}).then(function (response) {
console.log(response)
});
Where ubserObj.token -
Bearer Token ex: Bearer ASDF#!##!ADFASDF!##!##
This will be on the server side settings.
How to get the PayPal access-token needed to leverage the REST Api by using node?
Once you have a PayPal client Id and a Client Secret you can use the following:
var request = require('request');
request.post({
uri: "https://api.sandbox.paypal.com/v1/oauth2/token",
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"content-type": "application/x-www-form-urlencoded"
},
auth: {
'user': '---your cliend ID---',
'pass': '---your client secret---',
// 'sendImmediately': false
},
form: {
"grant_type": "client_credentials"
}
}, function(error, response, body) {
console.log(body);
});
The response, if successful, will be something as the following:
{
"scope":"https://api.paypal.com/v1/payments/.* ---and more URL callable with the access-token---",
"access_token":"---your access-token---",
"token_type":"Bearer",
"app_id":"APP-1234567890",
"expires_in":28800
}
Also, you can use axios, and async/await:
const axios = require('axios');
(async () => {
try {
const { data: { access_token } } = await axios({
url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
method: 'post',
headers: {
Accept: 'application/json',
'Accept-Language': 'en_US',
'content-type': 'application/x-www-form-urlencoded',
},
auth: {
username: client_id,
password: client_secret,
},
params: {
grant_type: 'client_credentials',
},
});
console.log('access_token: ', access_token);
} catch (e) {
console.error(e);
}
})();
Modern problems require modern solutions:
const fetch = require('node-fetch');
const authUrl = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
const clientIdAndSecret = "CLIENT_ID:SECRET_CODE";
const base64 = Buffer.from(clientIdAndSecret).toString('base64')
fetch(authUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Authorization': `Basic ${base64}`,
},
body: 'grant_type=client_credentials'
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data.access_token);
}).catch(function() {
console.log("couldn't get auth token");
});
You could use PayPal-Node-SDK to make calls to PayPal Rest APIs. It handles all the authorization and authentication for you.
Here is how I get the access_token using superagent
superagent.post('https://api.sandbox.paypal.com/v1/oauth2/token')
.set("Accept","application/json")
.set("Accept-Language","en_US")
.set("content-type","application/x-www-form-urlencoded")
.auth("Your Client Id","Your Secret")
.send({"grant_type": "client_credentials"})
.then((res) => console.log("response",res.body))
I'm trying to get an individual change event using;
GET
* https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('query')/item
Reference
http://msdn.microsoft.com/en-us/data/jj246759(v=office.12).aspx
And
http://msdn.microsoft.com/en-us/library/office/jj246759(v=office.15).aspx
I'm unable to get it working, and I can't find any example of this call.
I'm trying something like;
GET
https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('Add=true,Item=true')/item
https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges(query='Add=true,Item=true')/item
but no luck.
FYI:: I'm not trying to get changelogs with this call. I'm trying to get an individual change item. But since the syntax is like that I put a random query in the those braces. The /getchanges(which is a POST call) works fine.
Any help on this?
There are at least two options how to construct request for a ChangeCollection endpoint:
Option 1
Post ChangeQuery via request body
function getChanges(webUrl,queryOptions,success,failure)
{
var changeQueryPayload = {
'query':{
'__metadata': { 'type': 'SP.ChangeQuery' },
}
};
for(var key in queryOptions) {
changeQueryPayload['query'][key] = queryOptions[key];
}
$.ajax({
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify(changeQueryPayload),
url: webUrl + '/_api/web/getchanges',
success: success,
failure: failure
});
}
Option 2
Pass ChangeQuery expression via query string:
function getChanges(webUrl,queryOptions, success,failure)
{
$.ajax({
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
url: webUrl + '/_api/web/getchanges(#qry)?#qry=' + JSON.stringify(queryOptions) + ,
success: success,
failure: failure
});
}
Example
Retrieve updates for a web:
var queryOptions = {"Update":true,"Web":true};
getChanges(_spPageContextInfo.webAbsoluteUrl,queryOptions,
function(result){
var changes = result.d.results;
//print info
console.log('Found ' + changes.length + ' items');
},
function(error){
console.log(JSON.stringify(error));
});
Regarding requesting a specific change item, it could be retrieved from a results returned from REST service.
There is an example:
http://msdn.microsoft.com/en-us/library/office/dn499819(v=office.15).aspx
executor.executeAsync({
url: "<app web url>/_api/SP.AppContextSite(#target)/web/getchanges?#target='<host web url>'",
method: "POST",
body: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' }, 'Web': true, 'Update': true } }",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: successHandler,
error: errorHandler
});
Please refer https://msdn.microsoft.com/en-us/library/office/dn499819.aspx.
Following code is working for me.
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getchanges",
type: "POST",
data: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' },'Web': true, 'Update': true, 'Add': true } }",
headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose",'X-RequestDigest':$('#__REQUESTDIGEST').val() },
success: successHandler,
error: errorHandler
});
function successHandler(data, textStatus, jqXHR ){
alert("successHandler " + "textstatus:" +textStatus + "data: " + data);
}
function errorHandler(xhr, ajaxOptions, thrownError) {
alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
}