SolidJS Create Resource - Uncaught Error in Promise - solid-js

I'm new to SolidJS and I'm having a weird error with resources. Here is my code:
export const authUserResource = createResource(
() => axios.get<AuthUser>('/expense-tracker/api/oauth/user').then((res) => res.data)
);
export const MyComponent = () => {
const [data] = authUserResource;
createEffect(() => console.log('HasChecked', data.loading, data.error, data()));
return (
// ...
)
}
The intent of the API call is to retrieve data on the currently authenticated user, or to return a 401 if the user is not currently authenticated. My intent is to then redirect the user based on their authentication status.
Well, the API is called and it is returning a 401 because the user is not authenticated. All of this is expected. What is not behaving is the SolidJS resource.
If the API returns a 401, I would expect the SolidJS resource data to meet these conditions:
data.loading === false
data.error instanceof Error
data() === undefined
Instead, I am finding that it is still at these conditions, based on the console.log statement in the above code example:
data.loading === true
data.error === undefined
data() === undefined
I also get an "Uncaught Error in Promise" error message in the browser JS console.
I'm hoping to figure out what I am doing wrong here to make the resource correctly handle the error so that I can gracefully handle this in my application.

Related

Access HTTP Response Body on Axios GET Request Error

We are making a simple HTTP GET request to an API & noticing that when our HTTP requests error, the response body sometimes has more details then the error message. We are using the axios. We would like to access both the response and the error message from our code, but we are only seeing the error message and are unsure how to access the response. Here is our code:
Calling the API:
import { httpClient } from '../httpClient'; //AxiosInstance
type GetLocations = () => Promise<AxiosResponse<ILocation[]>>
const getLocations: GetLocations = async () => {
const url = `/Location`;
return httpClient.get(url);
}
const callAPI = async () => {
try {
const axiosResponse = await getLocations();
console.log(axiosResponse.data);
catch(error) {
// error.message has the error message, but we would like access to the http response body as well.
console.log(error)
}
}
Some Screenshots:
console.log(error):
The error object as JSON:
DevTools > Network > Our API Call > Response from same request that errored (has more info):
We would like to access this Incorrect syntax near ','. response from our catch block.

Using MongoDb Realm authentication within a React app

I am learning MongoDb Realm from the documentation and following the examples given. My code to login is
const loginEmailPassword = async (email, password) => {
const app = Realm.App.getApp(APP_ID)
const credentials = Realm.Credentials.emailPassword(email, password)
try {
// Authenticate the user
const user = await app.logIn(credentials)
return true
} catch (err) {
console.error('Failed to log in', err)
}
return false
}
If the credentials match a current user all is good, if the don't it doesn't throw an error but generates the following in the console:
POST https://eu-west-1.aws.stitch.mongodb.com/api/client/v2.0/app/<"my Realm App ID">/auth/providers/local-userpass/login 401
Failed to log in Error: Request failed (POST https://eu-west-1.aws.stitch.mongodb.com/api/client/v2.0/app/<"my Realm App ID">/auth/providers/local-userpass/login): invalid username/password (status 401)
Can anyone please help me understand what is going on?

Paypal sandbox post error 401 (Unauthorized)

enter image description hereI have been following a tutorial for a paypal sandbox using react-paypal-express-checkout and have followed it exactly, but when I try to open the paypal window it closes instantly and throws this error.
Photo:Photo Here
Text:
http.js:147 POST https://www.sandbox.paypal.com/v1/payment-experience/web-profiles 401 (Unauthorized)
types.js:121 Uncaught Error: Request to post https://www.sandbox.paypal.com/v1/payment-experience/web-profiles failed with 401 error. Correlation id: bfca9a9c3fdfc
{
"name": "AUTHENTICATION_FAILURE",
"debug_id": "bfca9a9c3fdfc",
"message": "Authentication failed due to invalid authentication credentials or a missing Authorization header",
"information_link": "https://developer.paypal.com/docs/api/payment-experience/#errors",
"details": []
}
at XMLHttpRequest.xhrLoad (http.js:114)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
_RECEIVE_MESSAGE_TYPE.<computed> # types.js:121
receiveMessage # index.js:114
messageListener # index.js:140
setTimeout (async)
dispatchPossiblyUnhandledError # exceptions.js:16
(anonymous) # promise.js:122
setTimeout (async)
reject # promise.js:120
dispatch # promise.js:179
reject # promise.js:127
dispatch # promise.js:179
reject # promise.js:127
dispatch # promise.js:186
reject # promise.js:127
(anonymous) # promise.js:157
dispatch # promise.js:184
reject # promise.js:127
(anonymous) # promise.js:51
respond # client.js:147
_RECEIVE_MESSAGE_TYPE.<computed> # types.js:126
receiveMessage # index.js:114
messageListener # index.js:140
serialize.js:175 Uncaught Error: Error: Request to post https://www.sandbox.paypal.com/v1/payment-experience/web-profiles failed with 401 error. Correlation id: bfca9a9c3fdfc
{
"name": "AUTHENTICATION_FAILURE",
"debug_id": "bfca9a9c3fdfc",
"message": "Authentication failed due to invalid authentication credentials or a missing Authorization header",
"information_link": "https://developer.paypal.com/docs/api/payment-experience/#errors",
"details": []
}
at XMLHttpRequest.xhrLoad (http.js:114)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at Object._RECEIVE_MESSAGE_TYPE.<computed> [as postrobot_message_response] (types.js:121)
at receiveMessage (index.js:114)
at messageListener (index.js:140)
at deserializeError (serialize.js:175)
at serialize.js:212
at util.js:140
at eachArray (util.js:102)
at each (util.js:116)
at replaceObject (util.js:138)
at util.js:147
at eachObject (util.js:109)
at each (util.js:118)
at replaceObject (util.js:138)
Heres the page for my button and all the tutorial guy changes is the sandbox id which I did:
import React from 'react';
import PaypalExpressBtn from 'react-paypal-express-checkout';
export default class MyApp extends React.Component {
render() {
const onSuccess = (payment) => {
// Congratulation, it came here means everything's fine!
console.log("The payment was succeeded!", payment);
// You can bind the "payment" object's value to your state or props or whatever here, please see below for sample returned data
}
const onCancel = (data) => {
// User pressed "cancel" or close Paypal's popup!
console.log('The payment was cancelled!', data);
// You can bind the "data" object's value to your state or props or whatever here, please see below for sample returned data
}
const onError = (err) => {
// The main Paypal's script cannot be loaded or somethings block the loading of that script!
console.log("Error!", err);
// Because the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js"
// => sometimes it may take about 0.5 second for everything to get set, or for the button to appear
}
let env = 'sandbox'; // you can set here to 'production' for production
let currency = 'USD'; // or you can set this value from your props or state
let total = 1; // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout
// Document on Paypal's currency code: https://developer.paypal.com/docs/classic/api/currency_codes/
const client = {
sandbox: 'ASloDPNYZO9LtigzQd58tcYQHuORCH3TlvPS-LWMdwzIWiEiefonUQE7KmWCE-WkaEaiiJb54RSNcrLE',
production: 'YOUR-PRODUCTION-APP-ID',
}
// In order to get production's app-ID, you will have to send your app to Paypal for approval first
// For sandbox app-ID (after logging into your developer account, please locate the "REST API apps" section, click "Create App"):
// => https://developer.paypal.com/docs/classic/lifecycle/sb_credentials/
// For production app-ID:
// => https://developer.paypal.com/docs/classic/lifecycle/goingLive/
// NB. You can also have many Paypal express checkout buttons on page, just pass in the correct amount and they will work!
return (
<PaypalExpressBtn env={env} client={client} currency={currency} total={total} onError={onError} onSuccess={onSuccess} onCancel={onCancel} />
);
}
}
The react-paypal-express-checkout repository does not reference v1/payment-experience/web-profiles , so I am not sure where your error is actually coming from
The v1/payment-experience/web-profiles API requires a valid ClientId and a Secret for authentication.

Result promise being processed before it executed on Ionic 2 Facebook login

I have an Ionic 2 application running the following code on an Angular 2 service:
signInWithFacebook(): firebase.Promise<any>
{
if (this.platform.is('cordova'))
{
console.log('Running on cordova...');
Facebook.login(['email', 'public_profile']).then(res =>
{
const facebookCredential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
console.log('credential value', facebookCredential);
var temp = firebase.auth().signInWithCredential(facebookCredential);
console.log('temp value: ', temp);
return temp;
});
}
else
{
return this.auth$.login({
provider: AuthProviders.Facebook,
method: AuthMethods.Popup
});
}
}
Then on my login component page I call it like this, on a login button:
pubic doFacebookLogin(): void
{
var temp = this.userDataService.signInWithFacebook()
.then(() =>
{
console.log("Passed here! [1]");
this.onSignInSuccess();
console.log("Passed here! [2]");
});
}
My console logs the following when I click the button:
Running on cordova...
main.js:46695 TypeError: Cannot read property 'then' of undefined
at LoginPage.doFacebookLogin (main.js:50920).....
credential value Lf {accessToken: "xxxxxx", provider: "facebook.com"}
temp value: I {F: 0, ka: undefined, o: I, fa: null, Ma: null…}
The flow I'm expecting is this:
call to the doFacebookLogin() method
call to the service.signInWithFacebook() method
Console logs 'Running on cordova...'
step [1] waits for the return promisse of [2]
call to Facebook.login(['email', 'public_profile'])
when the login on [4] is concluded, it calls the firebase.auth().signInWithCredential() method, which returns a promise too
Console logs 'credential value' and 'temp value'
the result promise of [5] is then returned on the service.signInWithFacebook() function
the doFacebookLogin() function finally processes the promise returned on [6] and execute onSignInSuccess()
But from the console logs we can see that it's logging 'Running on cordova', then we get an exception on the .then call of the first funcion (so the facebook login result promise was not yet processed (so the return promise doesn't exist), and after this the facebook login is processed (and now it exists, but the other function already tried to process it, generating the exception).
What am I missing with these promises?
It looks like you are just missing a return.
return Facebook.login(....).then(...);

Passport and SailsJS, how to get isAuthenticated() test to pass

My code keeps failing here when the user tries to login:
isAuthenticated: function (req, res) {
if (req.isAuthenticated()) { return res.json(req.user); }
else { return res.send(401); }
},
It FAILS and I get GET http://localhost:1337/user/authenticated 401 (Unauthorized) in the console, even though the user has entered in a correct email and password.
Where in the code makes that test pass?
I have the related StackOverflow question with more info HERE.
The problem was that my frontend application has a different origin than my backend application, so the AJAX requests will not include the session cookie and req.isAuthenticated() will never return true.
Use the withCredentials options to force it.
$http({ withCredentials: true, ... })