Create GitHub repo from node.js - javascript

I have this function in my node project, that should create a new GitHub repository for a specific user:
exports.create_repo = function (repo) {
var options = {
host: "api.github.com",
path: "/user/repos?access_token=" + repo.accessToken,
method: "POST",
json: { name: repo.name },
headers: { "User-Agent": "github-app" }
};
var request = https.request(options, function(response){
var body = '';
response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
response.on("end", function(){
var json = JSON.parse(body);
console.log(json);
});
});
request.end();
}
Every time I use it, the response is:
{ message: 'Not Found',
documentation_url: 'https://developer.github.com/v3' }
What do I do wrong ?

Related

x-www-form-urlencoded post parameters (body) in frisby npm not working

I'm trying to test rest endpoint 'http://xxxxxxx/j_spring_security_check' to get authentication with frisby npm package.
I am able to work in postman, by selecting request body as 'x-www-form-urlencoded' tab and given my app credentials like key-value, its working fine as expected. But in frisby npm I am unable to set request body as 'x-www-form-urlencoded'.
I'm unable to login with this script.
Please help me in this or any other alternative suggestions would be great.
Here is my code:
var frisby7=require('frisby');
const qs = require('qs');
describe('API reference', function() {
var baseURL='http://xxxxxx/j_spring_security_check';
it('Simple Test with post url-encode form body request ', function() {
console.log("**********")
frisby7.globalSetup({
request: {
headers:{'Content-Type':'application/x-www-form-urlencoded'}
// headers: { 'X-Ms-Source':'api','X-Ms-Format':'xml','Authorization':'Basic c2hyZXlhIGdveWFsOm0jbWY4cDlMZ2ZAMU1xUTg='}
}
});
return frisby7.post(baseURL,
{
form: { j_username:'xxxx#xxxxx.com', j_password:'xxxx' }
}).then(function (res) { // res = FrisbyResponse object
console.log('status '+res.status);
console.log('body '+res.body);
//return res;
});
});
You are currently sending the object in the body as if you were using 'multipart/form-data'.
To send the request as 'application/x-www-form-urlencoded' you need to URI encode each property and then post them as a querystring
Try it like this
var objToSend = { j_username:'xxxx#xxxxx.com', j_password:'xxxx' };
var uriObj = Object.keys(objToSend).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(objToSend[key])).join('&');
var url = baseURL + '?' + uriObj
frisby7.post(url);
Try something like this:
var frisby = require("frisby");
const Joi = frisby.Joi;
var req1 = {
method: "get",
url: "pass url here",
headers : {
"Accept": "application/json",
"content-type" : "application/json",
'Authorization': 'Basic ' + Buffer.from(username + ":" + password).toString('base64') // pass username and password for //validation
},
body: {}
};
describe('spec file name', function () {
it("spec file name" + dateTime, function(){
return frisby
.setup({ request: { headers : req1.headers } })
.get(req1.url)
.expect("status", 200)
.expect("header", "Content-Type", "application/json; charset=utf-8")
.expect("jsonTypes", {
"message": Joi.string()
})
.then(function(res) {
var body = res.body;
body = JSON.parse(body);
expect(body.message).toBeDefined();
})
.then(function(res) {
var body = res.body;
body = JSON.parse(body);
var req2 = {
method: "put",
url: "pass url here",
headers : {
"Accept": "application/json",
"content-type" : "application/json",
"Authorization": "JWT " + Token // anything that you using to authenticate
},
body: {}
};
return frisby
.setup({ request: { headers : req2.headers } })
.put(req2.url)
.expect("status", 200)
.expect("header", "content-type", "application/json; charset=utf-8")
.expect("jsonTypes", {
"message": Joi.string()
})
.then(function(res) {
var body = res.body;
body = JSON.parse(body);
expect(body.message).toBeDefined();
})
});
});
});

How to pass data with request module(POST method) on Node.JS?

I am following the following steps but getting an error. I think it is not passing the body. However get method was working fine with this steps.
var request = require("request");
var should = require("should");
var expect = require("chai").expect;
var baseUrl = "https://na73.salesforce.com/services";
const config = require("../../../lib/config");
const url = require("../../data/url");
describe('Get Call Record Resource list', function() {
this.timeout(config.timeOut);
it('Verify in Dialer Config api, able to get Dialer Config list', function(done) {
request.post({
headers: {
Authorization: `Bearer ${config.token}`
},
body:{
"callId": {
"callConnectService": "RING_CENTRAL",
"serviceCallId": "1564283263244352",
"externalId": "1564283263244352"
},
"appointmentId": "a181I000001IMOlQAO",
"entityId": "0031I00000MxBw8QAF",
"phoneNumberCalled": "+13175221101"
},
url: baseUrl + `${url.CallRecordResource}`
},
function(error, response, body) {
var bodyObj = JSON.parse(body);
expect(response.statusCode).to.equal(200);
expect(response.body).should.exists;
should.not.exist(error);
expect(response.body).to.not.be.undefined;
done();
});
});
});

Perform 3 tasks in a single api call

My current api call flow from my client is as follows:
Send data to brand endpoint, retrieve recently inserted id, assign to userData.brand
Send data to user endpoint, retrieve recently inserted id, assign to userData.user
Send both values to userBrand endpoint
This seems like a costly process, so I am thinking of consolidating all the requests into one, but I am not sure how to process it from the server side. I know that I can just use one endpoint, but I don't know to how to use all the serializers/views against one endpoint.
So on the client side, this is what I have:
In brand.js
AdsomaService.registerUser(vm.userData).then(function(data) {
vm.successMessage = data.message;
vm.userBrandData.user = data.id;
}, function error(data) {
$log.info(data);
vm.errorMessage = data;
errorCount++;
});
AdsomaService.registerUserBrand(vm.userBrandData).then(function(data) {
vm.successMessage = data.message;
}, function error(data) {
$log.info(data);
vm.errorMessage = data;
errorCount++;
});
if(errorCount > 0) {
vm.message = vm.errorMessage;
angular.element('#errorMessage').appendTo('body').modal('show');
} else if(errorCount === 0) {
vm.message = vm.successMessage;
angular.element('#successMessage').appendTo('body').modal('show');
}
In adsoma.js
function registerUser(userData) {
var url = envService.read('apiUrl') + '/user_signup/';
var dataJSON = {
email: userData.email,
password: userData.password,
account_type: userData.accountType
};
var req = {
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(dataJSON)
};
return ($http(req).then(handleSuccess, handleError));
}
function registerBrand(brandData) {
var url = envService.read('apiUrl') + '/brand_signup/';
var dataJSON = {
name: brandData.name,
brand: brandData.name,
email: brandData.email,
phone: brandData.phone,
website: brandData.website
};
var req = {
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(dataJSON)
};
return ($http(req).then(handleSuccess, handleError));
}
function registerUserBrand(userData) {
var url = envService.read('apiUrl') + '/user_brand_signup/';
var dataJSON = {
user: userData.user,
brand: userData.brand
};
$log.info(dataJSON);
var req = {
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(dataJSON)
};
return ($http(req).then(handleSuccess, handleError));
}
And on the server side, this is what I have:
In views.py
Code here: https://pastebin.com/P5ih75An.
In serialisers.py
Code here: https://pastebin.com/2zDgZDLc.

Post - Cannot GET error - Local server

I am trying to create an API using a local server for testing. The route
'GET' works fine, however 'POST' has a problem and it is returning 'Cannot GET /add/name'. I am developing the API using node.js and Express. Why am I receiving get when the route is set to 'POST'? Where is the problem?
var fs = require('fs');
var data = fs.readFileSync('events.json');
var allEvents = JSON.parse(data);
console.log(allEvents);
console.log('Server running.');
var express = require('express');
var app = express();
var sever = app.listen(3000, listening);
function listening() {
console.log('Serving...');
}
app.use(express.static('website'));
//GET and send all data from JSON
app.get('/all', sendAll);
function sendAll(request, response) {
response.send(allEvents);
}
//POST new data to JSON
app.post('/add/:name', addData);
function addData(request, response) {
var newData = request.params;
var name = newData.name;
var eventType = newData.eventType;
var reply;
// var newEvent = {
// name: ":name",
// eventType: ":eventType",
// };
var newData = JSON.stringify(allEvents, null, 2);
fs.writeFile('events.json', newData, finished);
function finished(err) {
console.log('Writting');
console.log(err);
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
Request
$(function() {
//HTML
var $list = $('#list');
var jsonURL = '../events.json'
$.ajax({
type: 'GET',
url: '/all',
success: function(data) {
console.log('Data received', data);
$.each(data, function (type, string) {
$list.append('<li>' + type + " : " + string + '</li>');
});
},
error: function (err) {
console.log('Error, data not sent.', err);
}
});
$('#submit').on('click', function () {
// var newEvent = {
// name: $name.val(),
// eventType: $eventType.val(),
// };
var name = $('#fieldName').val();
var eventType = $('#fieldEventType').val();
console.log(name);
$.ajax({
type: 'PUT',
url: '/add/' + name,
success: function (addData) {
$list.append('<li>name: ' + name + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
});
Thank you in advance.
For testing POST request, you can use Postman to test it. If you use the browser to call the api, it will be GET method instead of POST.

How to update ng-repeat list after http request

I am not able to update my ng-repeat list after I do PUT request. Service works fine.
controller.js
teamData.updateTeam(team.id, teamObj, function(res) {
console.log('Success');
});
service.js
teamService.updateTeam = function(teamId, param, callback) {
var req = {
method: 'PUT',
url: '/team' + teamId,
headers: {
'Content-Type': 'application/json'
},
'data': param
};
return $http(req).then(function(res){
callback(res);
}, function(err){
callback(err);
});
};
teamRoute.js
app.put('/team/:id', function(request, response) {
var options = {
host: reqParam.hostFramework,
path: reqParam.path + '/team/' + request.params.id,
method: 'PUT',
headers: {
'token': reqParam.token,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(JSON.stringify(request.body))
}
};
var resString = '';
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(d) {
resString += d;
});
res.on('end', function() {
response.send(resString);
});
});
req.write(JSON.stringify(request.body));
req.end();
});
team.html
<div ng-repeat="team in teamData">
<h2>{{team.name}}</h2>
....
</div>
My goal is to update the ng-repeat list just after PUT request is made (no page refresh). How can I achieve it?
Assign it back to the model. For example if your ng-repeat was on $scope.item then:
return $http(req).then(function(res){
callback(res);
$scope.item = res
}, function(err){
callback(err);
});

Categories

Resources