How to pass params through hapijs middleware to the routers - router

server.ext('onRequest', (request, reply) => {
//here is a param AA
const AA = 1234;
return reply.continue();
});
server.route({
method: 'GET',
handler: (request, reply) => {
//here i want to get param AA
reply('test');
};
});
how could i pass the params through middlerware to the router, like Params AA;

From the docs use request.app object to store application data
http://hapijs.com/api#request-properties
You can then access the object when inside your route handler.

Related

Axios sending url with params as string not object

i need to take url with params example:
https://domain.pl/ptpdf-gen?selected_posts=4871&advisor=magda,wojciech
But axios response is an object like:
{"https://domain.pl/ptpdf-gen?selected_posts":"4871","advisor":"magda,wojciech"}
How to send url as string via axios?
Optionally the request above could also be done as
axios.get('/user', {
params: {
selected_posts: 4871
advisor: ["magda", "Wojciech"]
},
paramsSerializer: params => {
return qs.stringify(params)
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
The qs is an external library,
https://www.npmjs.com/package/qs
var selected = 4871
var advisor = ["magda","wojciech"]
axios.post('https://domain.pl/ptpdf-gen', {selected, advisor })
So i made the url split like this, using URLSearchParams:
const currHref = window.location.search;
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('selected_posts');
const myParam2 = urlParams.get('advisor');
Then with axios.post i can send params:
axios.post("http://domain.pl/create", {myParam, myParam2})
On server i did handle params like:
const state = req.body;
const stateValues = Object.values(state);
And then i can concat url with stateValues[0] and stateValues[1];
let linkUrl = "https://domain.pl/ptpdf-gen?selected_posts=" + stateValues[0] + "&advisor=" + stateValues[1];
Works.

Add default data to Axios request

I am working on a project with React and a Rails API.
In each of my Axios requests, I want to pass a variable to my API.
Can I configure Axios to tell it to add a variable in the data when I try to POST, DELETE, PUT, PATCH…?
Example:
axios.post('url', { data: 'some_data' }).then(...)
→ API should receive:
data_of_request = { data: 'some_data', added_data_from_config_axios: 'some_variable' }
You can create your own function like this.
const sendPost = (url, data = {}, headers = {}) => {
var body = {...data, added_data_from_config_axios: 'some_variable' };
return axios.post(url, body, { headers });
}
And then, you use this function instead of axios
sendPost(url, { data: 'some_data' }).then(res => {
...
});
Finally I found a better answer.
I just used a built-in function of axios:
const added_data_axios = {
'add_data': '..some_data..'
};
const api = axios.create({
transformRequest: [(data) => {
return {...added_data_axios, ...data};
}, ...axios.defaults.transformRequest],
});

How to make http GET/POST request in ionic 2?

How to http GET/POST request in ionic2
and what are the data need to import ?
I tried with HTTP GET request in JavaScript? but it does not work for me.
GET Example
this.posts = null;
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot').map(res => res.json()).subscribe(data => {
this.posts = data.data.children;
});
console.log(this.posts);
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/
POST Example
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let body = {
message:"do you hear me?"
};
this.http.post('http://spstest.000webhostap..., JSON.stringify(body), {headers: headers})
.map(res => res.json())
.subscribe(data => {
console.log(data);
});
}
https://www.joshmorony.com/how-to-send-data-with-post-requests-in-ionic-2/
Good luck.
For Creating the request firstly we need to add provider by using this command :-
$ ionic g provider restService
here restService is the ts file name in which we write the below code for making request
load() {
console.log(' RestServiceProvider Load Method fro listing');
let postParams = { param1 : '', param2: '' }
if (this.data) {
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
this.http.post("YOUR URL", postParams)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
In the above code load() is the method of restService class.this method is help out to make the request .This method is called in your other class like this.
this.restSrvProvider.load().then(data => {
let mydata = data;
});
For more knowledge you may go through the ionic blog the

Port botbuilder restify listener to sailsjs route

I'm following the botbuilder demos here - https://github.com/Microsoft/BotBuilder/blob/master/Node/examples/demo-skype/app.js
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
I want to host this bot inside SailsJS.
I've routed the call as follows:
// config/routes.js
'POST /api/messages': {
controller: 'BotframeworkController',
action: 'listen',
},
And the controller:
var builder = require('botbuilder');
var botconfig = sails.config.botframework;
var connector = new builder.ChatConnector({
appId: botconfig.MICROSOFT_APP_ID,
appPassword: botconfig.MICROSOFT_APP_PASSWORD
});
var bot = new builder.UniversalBot( connector, function( session ) {
session.send("%s, I heard: %s", session.userData.name, session.message.text);
});
// Add help dialog
bot.dialog('help', function (session) {
session.send("I'm a simple echo bot.");
}).triggerAction({ matches: /^help/i });
module.exports = {
listen: function( req, res, next ){
sails.log.debug('BotframeworkController.listen... started');
sails.log.debug(req.body);
return connector.listen( req, res );
// var test = connector.listen( req, res );
// sails.log.debug(test );
},
}
I don't get any errors - that I can see - but there is no response returned to the client.
Any ideas/suggestions would be appreciated?
I haven't worked with SailsJS but it looks like it would call the listen method of BotframeworkController upon receiving a POST to /api/messages. Am I reading it right?
The connector.listen() itself is not the handler, it's the path to the handler. It returns a function that will handle the incoming request and response. Try it like this instead:
module.exports = {
listen: connector.listen()
}

How to use the login credentials with php in ionic project

I want to authenticate the user_name and password field. the user_name and password field is stored in database with php. how to get the data from the server in ionic project.
Thanks in advance.
You can create a service script that can send post data to PHP and receive a JSON response.
Post data should be sent as an object containing element name and values in the following format:
var myObj = {username: 'username', password:'password'};
Below is a service example:
yourApp.service('YourService', function ($q, $http) {
return {
login: function (data) {
var deferred = $q.defer(),
promise = deferred.promise;
$http({
url: 'http://www.example.com/yourPHPScript.php',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
if (response.data.error.code === "000") {
deferred.resolve(response.data.appointments);
} else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error);
});
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
return promise;
}
};
});
From your login controller you call the following code to use the service (make sure you add the name of the service to your controller declaration)
YourService.login(loginData)
.then(function (data) {
// on success do sthg
}, function (data) {
//log in failed
// show error msg
});