aurelia aurelia-http-client jsonp - javascript

I try to query an api which is not the same origin with the aurelia-http-client.
My code pretty simple :
import {HttpClient} from 'aurelia-http-client';
export class App {
constructor(){
console.log("constructor called");
let url = 'http://localhost:8081/all';
let client = new HttpClient();
client
.jsonp(url)
.then(data => {
console.log("datas");
console.log(data);
});
}
}
Nothing happens, I can see in network that the url is called, my api engine logs an entry but I never enter in the "then" of the "promise"...
What's wrong ?
Update :
I give you some screenshots with catch
code source
browser result
With JQuery on the same machine no problems.

After reading this post other jsonp case I try to add the work "callback" and now it works !!!
so call jsonp(url, 'callback')
client.jsonp(url, 'callback')
Thanks...

This may not be a direct answer but just a suggestion, I would rather use the aurelia API as I found it more consistent and stable.
just add it as plugin in you main :
.plugin('aurelia-api', config => {
config.registerEndpoint('github', 'https://api.github.com/');
});
and use it as:
import {Endpoint} from 'aurelia-api':
#autoinject
export class Users{
constructor(private githubEndpoint){
}
activate() {
return this.githubEndpoint.find('users')
.then(users => this.users = users);
}
}
Source: https://aurelia-api.spoonx.org/Quick%20start.html

Related

Why won't my simple get request with axios return what the controller's returning?

I'm learning Laravel with React.js but I can't figure out why my simple get request won't work. I get a 404 error. I've seen a similar question asked on SO and I've tried running composer require barryvdh/laravel-cors on the command line but it still doesn't work.
How can I rectify this?
Here's react code:
constructor(props) {
super(props);
this.axiosGet = this.axiosGet.bind(this);
}
axiosGet(e) {
e.preventDefault();
axios.get('/thank-you')
.then(response => {
console.log(response);
});
}
render() {
<Form onSubmit={this.axiosGet}>
...
</Form>
}
Here's api.php
use App\Http\Controllers\MailController;
Route::get('/thank-you', [MailController::class,'index']);
Here's MailController.php
public function index() {
return "Testing";
}
your route is /api/thank-you. When you are using API routes. API comes in front of your routes.
Change your axios.get('/thank-you') as axios.get('/api/thank-you')

Ember.JS concurrency task, perform() is not a function

I was trying to convert a function over to a task. Here is the original code:
Call:
this.socketConnect(endpoint, token);
Function:
socketConnect = async (token, endpoint) => {
this.socket = new WebSocket(endpoint + '?auth=' + token);
this.socket.addEventListener('open', () => {
this.socket.addEventListener('message', event => this.handleMessage(event));
this.socket.addEventListener('close', event => this.retryConnection(event, endpoint));
});
}
I've been following structure on implementing Ember tasks. It all compiles with no issue, however when it gets called, it outputs that this.socketConnect(...) is not a function. Before hand I didn't have the return below and it output that this.socketConnect wasn't a function. Here is my current code for a task.
Import:
import { task } from 'ember-concurrency';
Call:
this.socketConnect(endpoint, authToken).perform();
Function:
#task *socketConnect(endpoint, token) {
yield async () => {
this.socket = new WebSocket(endpoint + '?auth=' + token);
this.socket.addEventListener('open', () => {
this.socket.addEventListener('message', event => this.handleMessage(event));
this.socket.addEventListener('close', event => this.retryConnection(event, endpoint));
});
return;
};
}
New to this, so I'm guessing there's something small I'm missing. It matches other uses. Also if anyone could help on the benefits of switching a websocket generation function to a task? Any help would be appreciated, thank you.
The #task decorator isn't part of the official ember-concurency package yet. The official version lives in ember-concurrency-decorators for now. You'll need to
ember install ember-concurrency-decorators
and then you can do
import { task } from 'ember-concurrency-decorators';
To use it.
Alternatively you can use a different syntax if you don't want another dependency.
import { task } from 'ember-concurrency';
class Foo {
#(task(function*() {
// ...
}).restartable())
doStuff;
executeTheTask() {
this.doStuff.perform();
}
}
To call the task the syntax is:
this.socketConnect.perform(endpoint, authToken);
As you're not calling socketConnect directly, you want to call the method that ember concurrency generates for you.

Handing C# .NET events with edge.js in Node.js for electron

I need to do some calls from my js to my C# DLL in my Electron project and it works fine in this way:
c#
namespace Electron.Wrapper
{
public class QueryWrapper
{
public async Task<object> OnQuery(dynamic request)
{
...
return ..;
}
}
}
js
let edge = require('electron-edge-js');
let queryWrapperQuery = edge.func({
assemblyFile: '..dllUrl..',
typeName: 'Electron.Wrapper.QueryWrapper',
methodName: 'OnQuery'
});
window.query = function (options) {
queryWrapperQuery(JSON.stringify(options), function (error, result) {
...
});
}
The problem is that I use an external DLL that triggers async events sometimes, so I need find a way for listening the .NET events from js.
I found this way for resolve my problem but I think isn't the right way because I need a class library for Electron and I don't know how use it with also the previous way and probabily I don't need a WebSocketServer.
A .Net and js sample will be valued.
Thanks,
Andrea
Update 1
I found this way, cold be the right one? I'm trying to implement .net, any suggestions?
I found a good way:
C#:
public Task<object> WithCallback(IDictionary<string, object> payload)
{
Func<object, Task<object>> changed = (Func<object, Task<object>>)payload["changed"];
return Task.Run(async () => await OnQuery(payload["request"], changed));
}
js:
var withCallback = edge.func({
assemblyFile: '..dllUrl..',
typeName: 'Electron.Wrapper.QueryWrapper',
methodName: 'WithCallback'
});
window.query = function (options) {
function triggerResponse(error, result) {
...
}
withCallback({
changed: (result) => triggerResponse(null, result),
request: JSON.stringify(options)
}, triggerResponse);
};
When you need trigger when someting changes you should use the parameter 'payload' in OnQuery function:
public async Task<object> OnQuery(dynamic request, dynamic payload = null)
{
...
}
Next the OnQuery return the value you can call again the js callback in this way:
payload("Notify js callback!");
I hope this can help someone!

Implementing a custom ember-simple-auth Authenticator

Firstly, I am not a seasoned JS Developer, so please excuse obvious mistakes that I could have made.
I am trying to implement a custom Authenticator for authenticating a user with Keycloak using the OAuth2 Password Grant which requires the client_id be passed as part of the request body.
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default OAuth2PasswordGrant.extend({
serverTokenEndpoint: 'http://localhost:8080/something/token',
makeRequest(url, data, headers = {}) {
data.client_id = 'my-app';
return this._super(url, data, headers);
}
});
I have a controller that uses this Authenticator by calling this action:
actions: {
authenticate() {
let {username, password} = this.getProperties('username', 'password');
this.get('session').authenticate('authenticator:oauth2', username, password).then(() => {
// Do something
}).catch((response) => {
// Show error
});
}
}
This causes Firefox to hang and gives me an unresponsive script message.
If I remove the return from the makeRequest() method, I can see from the browser debugger that the call to Keycloak actually returns correctly with the object that contains my token etc. However ember inspector shows some errors related to unresolved promises. But I guess that's because I'm no longer returning the promise.
What am I doing wrong here?
How can I fix the unresponsive script issue?
Is there another way for me to achieve my goal?
Edit 1: This is when I remove the return
Here is the actual object that is returned:
{
"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCIg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WwfaHeY1yZZuwnQ5bj-0IHP4UEmiPTqaeCE1KVyjl3kZz3HJVisndtcKPr05kalS-M_NqU0TaYvbcZ_zesJRIga5sz4gGRqObUmUCUJoQ_iWoOhbM2SutiVnlfgJDACvOxegIcSvakZTgQsEcSweio_0kMFqi-2DYzFp6Rl0TpQ8vALLkc7rEOonUGyt7S4qQzkT-xB1_ZDlSVfm6mC-QKYNZhtqBT18P7MKxBhEgwrJtCytA_4ft7qNAbgvZ3kUohcbhzxGvtHej5RKHNI2wTzwK3IWHbkLWNndxSk_Lzj2-lCx380VpTkVpiDJfq5umjskOmI13dyPF7paA",
"token_type":"bearer",
"not-before-policy":0,
"session_state":"40831eaa-4f2a-496e-945d-7beb17e46e44"
}
This is what ember inspector (Promises) shows:
Here is the stacktrace from the Promise:
Ember Inspector ($E): authenticate/<#http://localhost:4200/assets/vendor.js:77927:9
initializePromise#http://localhost:4200/assets/vendor.js:63591:7
Promise#http://localhost:4200/assets/vendor.js:64067:35
authenticate#http://localhost:4200/assets/vendor.js:77919:14
authenticate#http://localhost:4200/assets/vendor.js:78528:14
authenticate#http://localhost:4200/assets/vendor.js:79420:14
authenticate#http://localhost:4200/assets/sfx-itransfer-web-agent.js:855:9
join#http://localhost:4200/assets/vendor.js:20249:24
run$1.join#http://localhost:4200/assets/vendor.js:37657:12
makeClosureAction/</<#http://localhost:4200/assets/vendor.js:29073:16
exports.flaggedInstrument#http://localhost:4200/assets/vendor.js:37087:14
makeClosureAction/<#http://localhost:4200/assets/vendor.js:29072:15
submit/<#http://localhost:4200/assets/vendor.js:70453:20
tryCatch#http://localhost:4200/assets/vendor.js:63549:14
invokeCallback#http://localhost:4200/assets/vendor.js:63562:15
publish#http://localhost:4200/assets/vendor.js:63532:9
#http://localhost:4200/assets/vendor.js:54458:16
invoke#http://localhost:4200/assets/vendor.js:19948:17
flush#http://localhost:4200/assets/vendor.js:19827:25
flush#http://localhost:4200/assets/vendor.js:20019:25
end#http://localhost:4200/assets/vendor.js:20128:26
run#http://localhost:4200/assets/vendor.js:20212:21
join#http://localhost:4200/assets/vendor.js:20219:24
run$1.join#http://localhost:4200/assets/vendor.js:37657:12
handleEvent/<#http://localhost:4200/assets/vendor.js:58233:18
exports.flaggedInstrument#http://localhost:4200/assets/vendor.js:37087:14
handleEvent#http://localhost:4200/assets/vendor.js:58232:17
_Mixin$create.handleEvent#http://localhost:4200/assets/vendor.js:57385:12
_bubbleEvent#http://localhost:4200/assets/vendor.js:57685:14
setupHandler/<#http://localhost:4200/assets/vendor.js:57619:20
dispatch#http://localhost:4200/assets/vendor.js:5546:16
add/elemData.handle#http://localhost:4200/assets/vendor.js:5355:6
Actually you solution looks like right.
I guess you have a problem in server response or mismatch request methods GET/POST. To solve this try to debug promise inside makeRequest.
return new RSVP.Promise((resolve, reject) => {
fetch(url, options).then((response) => {
response.text().then((text) => { //<-- here debug text
let json = text ? JSON.parse(text) : {};
if (!response.ok) { //<-- and here debug response
response.responseJSON = json;
reject(response);
} else {
resolve(json);
}
});
}).catch(reject);
So if problem will here, just rewrite whole method of makeRequest and add you own promise with custom fetch.
Another way is to write custom Authenticator, overriding authenticate, restore and (optionally) invalidate methods as wrote in documentation: https://github.com/simplabs/ember-simple-auth#implementing-a-custom-authenticator

Ember CLI + Ember Data + Simple Auth: authorize gets not called

i am using Ember CLI + Ember Data + Simple Auth. The authenticator is working fine. But when im am doing a Rest Call with Ember Data Rest Adapter this.store.findAll("user"); the authorize function in my custom authorizer don't gets called.
The Rest API Endpoint is on an other domain, so i added the url to the crossOriginWhitelist in my environment.js.
environment.js:
module.exports = function(environment) {
var ENV = {
// some configuration
};
ENV['simple-auth'] = {
crossOriginWhitelist: ['http://api.xxxx.com'],
authorizer: 'authorizer:xxxx',
routeAfterAuthentication: 'dashboard',
};
return ENV;
};
authorizer
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
var XXXXAuthorizer = Base.extend({
authorize: function(jqXHR, requestOptions) {
// Some Code, gets not called, damn it :(
}
});
export default {
name: 'authorization',
before: 'simple-auth',
initialize: function(container) {
container.register('authorizer:xxxx', XXXXAuthorizer);
}
};
index.html
....
<script>
window.XXXXWebclientENV = {{ENV}};
window.ENV = window.MyAppENV;
window.EmberENV = window.XXXXWebclientENV.EmberENV;
</script>
<script>
window.XXXXWebclient = require('xxxx-webclient/app')['default'].create(XXXXWebclientENV.APP);
</script>
....
Thanks for help :)
I had a similar problem. For me it was the crossOriginWhitelist config.
I set it like this:
// config/environment.js
ENV['simple-auth'] = {
crossOriginWhitelist: ['*'] // <-- Make sure it's an array, not a string
};
to see if I could get it working (I could), then I could narrow it down to figure out exactly what URL I should use to enforce the restriction (port number and hostname etc).
Don't leave it like that though!
You should actually figure out what URL works for the whitelist, and use that.
I am facing the same issue. I have same setup but the authorize function is not being called. May be you can try by adding the port number in your crossOriginWhiteList url.
I am adding window.ENV = window.MyAppENV line in new initializer which runs before simple-auth. You have added that in index file and may be that is the reason why simple-auth is not able to read your configuration.
Does the other configuration routeAfterAuthentication: 'dashboard', works properly? If not then this might be the reason. Try adding new initializer like
export default {
name: 'simple-auth-config',
before: 'simple-auth',
initialize: function() {
window.ENV = window.MyAppNameENV;
}
};

Categories

Resources