How do I post data using $resource using angularjs - codeigniter

I'm having a bit of a problem, I'm trying to do a http post request to my backend php. I'm new to angular and wanted to try the different REST method. I'm good with GET method. After this I will try UPDATE and DELETE method but for now I'm stuck on this. T__T.
Here a bit of the code in php
$data = array(
"email" => $email,
"password" => $this->input->post("password")
);
$insert_data = $this->player_registration->insert($data);
And here my factory
angular.module('myApp.services', ['ngResource'])
.factory('webService', function($resource){
var apiUrl = "http:domain.com/feed/"; //change this to web service
var factory = {};
factory.registerPlayer = function() {
return $resource( apiUrl + ':type', {type:'player'}, {
post: {method:'POST', params: {}}
});
};
factory.getPlayerByEmail = function () {
return $resource( apiUrl + ':type', {type:'player'}, {
get: {method: "GET", params: {}}
});
};
return factory;
})
And my controller
function registerController($scope, webService) {
$scope.inputs = {};
$scope.inputs.email = "testuser#domain.com";
$scope.inputs.password = "password";
var req = new webService.registerPlayer($scope.inputs);
req.save()
My app.js
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers'])

The default save() in $resources is actually $save().
var req = new webService.registerPlayer($scope.inputs);
req.$save()

Related

AdonisJS Socket.IO JWT authentication

How can you define the auth provider? Now every time the auth variable is undefined in the playerLogin method.
I'm are using Adonis v4.1
The code:
start/socket.js
const Server = use('Server')
const io = use('socket.io')(Server.getInstance())
// Define controllers here
// Example: const WSController = use('App/Controllers/Http/ChatController')
const AuthenticateController = use('App/Controllers/Http/AuthenticateController');
io.on('connection', function (socket) {
// Define here the controller methods
// Example: WSController.goMessage(socket, io)
AuthenticateController.playerLogin(socket, io);
AuthenticateController.playerRegister(socket, io);
})
AuthenticateController.js
const Hash = use('Hash')
const User = use('App/Models/User')
class AuthenticateController {
static playerLogin(socket, io, {auth}) {
socket.on('playerLogin', async (data) => {
console.log('WORKS')
if (await auth.attempt(data.email, data.password)) {
let user = await User.findBy('email', data.email)
let accessToken = await auth.generate(user)
socket.emit('sendPlayerToken', { token: accessToken });
} else {
socket.emit('sendPlayerToken', { token: 'Credentials are incorrect' });
}
});
}
static playerRegister(socket, io) {
socket.on('playerRegister', async (data) => {
const safePassword = await Hash.make(data.password)
const user = new User()
user.username = data.username
user.email = data.email
user.password = safePassword
await user.save()
socket.emit('sendPlayerRegister', { success: true });
});
}
}
Kind regards,
Corné
As this discussion bellow:
https://github.com/adonisjs/core/discussions/2051?sort=new#discussioncomment-274111
You can use the API guard and authenticate using the code from the answer of M4gie.
You only need to install the crypto package with yarn add crypto and if you don't want to create the object to display the socket errors, just turn it into a string: throw new Error('SocketErrors:MissingParameter').

How to access lex session attributes in AWS lambda function

I wrote the below code to assign session attributes from my application,
var lexruntime = new AWS.LexRuntime();
var params = {
botAlias: 'PizzaOrder', /* required */
botName: 'PizzaOrder', /* required */
inputText: 'profile list', /* required */
userId: '160728846416', /* required */
sessionAttributes: {
//'<token>': cookies['token'],
'token': cookies['token'],
'communityid':cookies['communityid'],
'selectedAuthorId':cookies['selectedAuthorId'],
'kfurl':cookies['kfurl']
/* '<String>': ... */
}
};
//console.log("Cookies in index js "+cookies['token']);
lexruntime.postText(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
I want to access the session attributes in my lambda function using intentRequest.sessionAttributes.seesionattributename in the below code and as shown below
function GetAuthors2(intentRequest,callback) {
const token2 = String(intentRequest.sessionAttributes.token);
const communityid2 = String(intentRequest.sessionAttributes.communityid);
// --------- http start ---------
var options = {
hostname: 'kf6-stage.rit.albany.edu',
port: 443,
path: '/api/communities/'+communityid2+'/authors',
headers: {
'Content-Type' : "application/json",
'Authorization' : "bearer " + token2
}
};
https.get(options, (resp) => {
console.log("#in Http");
let data2 = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data2 += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
var data_2 = JSON.parse(data2);
const cList2 = [];
data_2.forEach(function(i){
cList2.push(i.firstName);
});
callback(close(intentRequest.sessionAttributes, 'Fulfilled',
{
contentType: "PlainText or SSML",
content: "Hi,You have "+cList2.length+" authors registered Bharghav. Here is the list \n"+ cList2.join()
}
));
});
});
}
but after the intent request I am getting the following response "Sorry, I was unable to process your message. Try again later."
If I hardcode the values in the lambda function it works fine.
Can someone kindly tell me where am I doing wrong in accessing the session attributes??
This worked for me. accessing the session attributes from the event/input. Then accessing the attribute by name.
exports.handler = async (event) => {
var attributes = event['sessionAttributes'];
console.log('attrs; ',attributes);
let sessValue;
if( attributes != null)
sessValue = attributes['fileName'];

how to post associative array in ionic 3

When i try to post a data in associative array to rest api using ionic.
Only empty data receive in server side.
Is this method is correct or suggest any other method
public login(credentials) {
let apiUrl = this.urlService.apiUrl + 'oauth/access_token';
let headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded'});
let options = new RequestOptions({
headers: headers});
var postcredn=new Array();
postcredn['username'] = "karthik#abcde.in";
postcredn['password'] = "05550";
postcredn['grant_type'] = "password";
postcredn['client_id'] = "Outfit1548669";
postcredn['client_secret'] = "a10620c85033abd17716cda245";
console.log('iii'+postcredn['username'] );
return new Promise((resolve, reject) => {
this.http.post(apiUrl, postcredn, options)
.subscribe(res => {
resolve(JSON.parse(JSON.stringify(res)));
console.log('json'+ JSON.stringify(postcredn));
}, (err) => {
reject(err);
console.log(apiUrl);
});
});
}
} console.log(apiUrl);
});
});
}
}
Thanks in advance
Please rewrite following code:
First you need to create interface like:
export interface Postdata{
username: String;
password:String;
grant_type:String;
client_id: String;
client_secret: String;
}
Then import it and set its value:
var postcredn:Postdata;
postcredn={
username:'karthik#abcde.in',
password:'05550',
grant_type:'password',
client_id:'Outfit1548669',
client_secret:'a10620c85033abd17716cda245'
}
Finally post it via post method:
return new Promise((resolve, reject) => {
this.http.post(apiUrl, postcredn, options)
.subscribe(res => {
resolve(JSON.parse(JSON.stringify(res)));
console.log('json'+ JSON.stringify(postcredn));
}, (err) => {
reject(err);
console.log(apiUrl);
});
});
Associative arrays in Javascript are technically Objects and can't be instantiated via new Array(). To create one you can use any of new Object() or {}. So from the code you posted, you will define it as var postcredn=new Object(); or var postcredn={};
In your Laravel code, you can access it as you would an associative array in PHP.

Dialogflow v2 Actions on Google response timeout

Hi I have a timeout problem to get a json response; I am using google places API to look for the closest location.
Could anyone help me with this? Thanks.
const PlaceSearch = require("./node_modules/googleplaces/lib/NearBySearch.js");
const PlaceDetailsRequest = require("./node_modules/googleplaces/lib/PlaceDetailsRequest.js");
app.intent('Ask Location', conv => {conv.ask(new Permission({context: 'To start',permissions: 'DEVICE_PRECISE_LOCATION',}));});
app.intent('geolocation.intent', (conv,params,granted) =>{
if(granted){
var coordinates = conv.device.location.coordinates;
var location = [coordinates.latitude, coordinates.longitude];
var searchParameters = {
location: location,
name:'Store Name',
radius:10000
};
var config = {
apiKey:'#####',
outputFormat:'json'
};
var placeSearch = new PlaceSearch(config.apiKey, config.outputFormat);
var placeDetailsRequest = new PlaceDetailsRequest(config.apiKey, config.outputFormat);
placeSearch(searchParameters, function (error, search_response) {
if(search_response.status === 'OK'){
placeDetailsRequest({reference: search_response.results[0].reference}, function (error, details_response) {
conv.ask(`Your closest store is at ${details_response.result.formatted_address}.`);
});
}
});
}
});
I solved the issue using a request to Google API via URL; and using a promise.
const request = require("request");
app.input("geolocation.intent", conv => {
return new Promise((resolve, reject) => {
...
request(options, (error, response, body) => {
...
if (error) {
...
reject(...);
} else {
...
resolve(...);
}
}).then(result => {
const address = result.address;
conv.ask('Your closest store is...');
}).catch(error => {
conv.close('Error in Promise');
});
});
What I learned is that in Dialogflow API v2 you need to use promises when you make a request.

koa2 post always show Method Not Allowed?

//server.js
const Koa = require('koa')
const app = new Koa();
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
const Router = require('koa-router');
const fs = require('fs');
const router = new Router();
const UserController = require('./server/controller/user.js');
const checkToken = require('./server/token/checkToken.js');
router.get('/user/login', async ctx => {
ctx.body = JSON.parse(fs.readFileSync( './pass.json'));
console.log(ctx.body);
});
router.post('/signin', async (ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p>Try again</p>`;
}
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8090, () => {
console.log('The server is running at http://localhost:' + 8090);
});
koa:2.52
koa-bodyparse:4.21
koa-router:7.4
when I type http://localhost:8090/user/login can get the Json data,but type http://localhost:8090/signin always show 405 Methods Not Allowed ,(debian firefxo) show Request Method "GET",response Allow: POST,Connection: "keep-alive"
I hope get your help.
I guess you shouldn't use the chrome to do the post cause when you type some url, the default method is GET not POST, you can check it out from the NETwork。 Try postman it will work.Sorry for my bad english,I hope it will help XD

Resources