My .NET api which was working perfectly well with .NET 6.x is not working with .NET 7. I can make http requests with Thunder Client and Swagger but it won't work with my React Native (expo) app. I tried it with Flutter as well and that didn't work. I get this error:
Possible Unhandled Promise Rejection (id: 1):
I'm using Axios to make the request. My appsettings.json looks like this:
...
"Kestrel": {
"Endpoints": {
"Http":{
"Url": "http://localhost:5000"
},
"Https":{
"Url": "https://localhost:5001"
}
}
},
...
My API call looks like this:
const baseUrl = 'https://localhost:5001/api/users';
const headers = {
"Content-Type": "application/json",
}
const [user, setUser] = useState(null);
useEffect(() => {
axios.get(baseUrl, {headers}).then((response) => {
setUser(response.data);
console.log(response.data);
}).catch(function(error){
console.log(error);
console.log(error.response.data);
});
}, []);
I have enabled CORS in by Program.cs
...
builder.Services.AddCors(options =>
{
options.AddPolicy(name: CorsPolicy,
policy =>
{
policy.WithOrigins
(
"exp://192.168.0.41:19000",
"http://localhost:19006",
"http://localhost:19000"
)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
...
app.UseCors(CorsPolicy);
...
Is this an issue with .NET 7.0 or is it just coincidence? How can I fix it?
react-native will not work with localhost calls use ngrok to handle this
Related
I am using fetch to call backend API, th eprobelm is the backend security is a token, for security purpose we can not expose this token on public configuration.
I wanted to know if it is possible to put the token on server side params and then when we call fetch params is not visible in chrome debug and use only on NITRO following this text
Nitro allows 'direct' calling of routes via the globally-available $fetch helper. This will make an API call to the server if run on the browser, but will directly call the relevant function if run on the server, saving an additional API call.
$fetch API is using my fetch, with key features including:
This is my code
let recipientWebDTO = {};
recipientWebDTO.email = this.form.email;
recipientWebDTO.subscriptions = [{
"mailingListUnid": useRuntimeConfig().UNID
}];
const { status } = await $fetch
.raw(useRuntimeConfig().public.REST_API, {
method: "POST",
body: recipientWebDTO,
headers: {
"Content-Type": "application/json",
Authorization: useRuntimeConfig().TOKEN,
},
})
.then((response) => ({
status: response.status,
}))
.catch((error) => ({
status: error?.response?.status || 500,
}));
And my config file
export default defineNuxtConfig({
runtimeConfig: {
UNID: '58',
COMPANY_UNID: '3',
TOKEN: '78f77',
public: {
REST_API: process.env.REST_API || 'http://localhost:8080/rest/mailinglist/register/v1'
},
},
css: ["#/assets/_main.scss"],
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: '#use "#/assets/_colors.scss" as *;'
}
}
}
}
})
I want UNID, COMPANY_UNID, TOKEN to be visible only on server side, here it is just undefined, have I to create a middleware to handle it ? If yes, how I can use the same project to make it work ?
To manage to do it i added a server part as it is explained here:
Server api nuxtjs3 documentation
I created a directory server/api then my ts file with my proxy call where i use my token. Then in my vue i call my api. it means on browser the server file is invisible, and parameters and token nt accessibles.
in my vue:
const { status } = await $fetch.raw( '/api/newsletter', { method: "POST", body: this.form.email } )
in my server file:
export default defineEventHandler(async (event) => {
const runtimeConfig = useRuntimeConfig();
const subscriber = await readBody(event);
console.log("url used for rest call" + runtimeConfig.REST_API);
let recipientWebDTO = {
email: subscriber,
subscriptions: [{
"mailingListUnid": runtimeConfig.UNID
}]
};
const status = await $fetch.raw(runtimeConfig.REST_API, {
method: "POST",
body: recipientWebDTO,
headers: {
Authorization: runtimeConfig.TOKEN,
},
}).then((response) => ({
status: response.status,
}))
.catch((error) => ({
status: error?.response?.status || 500,
}));
return status;
})
The only complexity i have is i wanted to get a specific status but i always have the api call status, is 200 i wanted to simply forward the result but in NUXTJS is in WIP.
The issue I'm having here is that whenever I deploy my app to either Netlify or Vercel the POST requests specifically being sent to the NextJS APIs are all throwing this error;
ERROR SyntaxError: Unexpected token ' in JSON at position 0
however, when I run the application in either development mode or by building and running locally I'm not having the same issue everything works perfectly.
This is the code I'm using to send the request;
fetch('api/route', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ... data })
})
.then(res => res.json())
.then(data => {
data.error ? reject(new Error(data.error)) : resolve(data)
})
.catch(err => {
console.log(err)
reject(new Error('Network Error'))
})
And, this is an example of the code in the API files;
export default async function handler(req, res) {
const { method } = req
switch (method) {
case 'POST':
const { ... data } = req.body
try {
// Computation
res.status(200).json({ message: 'OK' })
} catch (error) {
console.log(error)
res.status(500)
}
break;
default:
// Invalid Method
console.log(new Error('Invalid Method: ', method))
res.status(405)
}}
I would really appreciate any assistance, I'd really like to know what the problem is.
I'm using RTKQuery to fetch data as following:
export const productsApi = createApi({
reducerPath: 'productsApi',
baseQuery: fetchBaseQuery({
baseUrl: BASE_URL,
prepareHeaders,
}),
tagTypes: ['Products'],
keepUnusedDataFor: 8600,
endpoints: builder => ({
getProperties: builder.query<IProduct[], IParams>({
query: params => ({ url: 'products', params: { per_page: 40, ...params } }),
transformResponse: ({ data }: { data: IProduct[] }) => data,
providesTags: ['Products'],
}),
});
I am relatively new to Redux Toolkit and started it using directly before using any of Redux. From the ReduxToolkit documentation, I'm finding 2 ways to catch and put actions on the backend.
Using Async thunk.
Middleware
I tried using the code as follows with the Middleware approach:
export const rtkQueryErrorLogger: Middleware = (api: MiddlewareAPI) => next => action => {
if (isRejected(action)) {
console.log(action);
}
return next(action);
}
But this does not catch the 40x/50x errors. What should be the way to handle this?
The purpose is to say send logs to the server upon catching these errors with meta-information. I was following: https://redux-toolkit.js.org/rtk-query/usage/error-handling#handling-errors-at-a-macro-level as a reference.
I Have configured the signalr with ASP NET core. When i use local service, it works properly. When i use after host it's not working as expected throws the below error.
Here is the code that i have done.
import * as signalR from '#microsoft/signalr';
const connection: signalR.HubConnection = new signalR.HubConnectionBuilder().withUrl('wss://demo/staging/web-services/hubs/spreadsheethub',
{
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets,
}).build();
...
});
connection.on('dataReceived', (data: string) => {
// code
});
connection.start().then(() => {
console.log('server connected!!!');
}).catch(err => console.log(err));
Is it possible to use phone authentication with Firebase and Ionic 4 in mobile apps?
I have seen some old tutorials implementing phone authorization with Ionic 3, but these seem to be outdated.
The firebaseui-web project does not support phone authentication for cordova apps, but I am unsure if that implies that Firebase phone authentication is impossible with ionic apps.
If you cannot use Firebase's phone authentication with Ionic 4, is there an alternative phone authentication service that does work with Ionic 4?
Yes. You can do it with Firebase's Javascript SDK, it will need the user to pass a CAPTCHA and then send the phone number a verification code which you can login and auth with, the process is explained here:
https://firebase.google.com/docs/auth/web/phone-auth#send-a-verification-code-to-the-users-phone
The problem is that the firebase auth sms service will only send messages when the app is in production mode (uploaded to the store). But to be able to test the methods from test mode, it is adding a test number in the white list of firebase.
In my case, I try these:
sms-verification.page.ts
sendSmsVerification(phoneNumber): Promise <firebase.auth.UserCredential> {
return new Promise((resolve, reject) => {
firebase.auth().useDeviceLanguage();
var verificationId;
var code;
const timeOutDuration = 60;
const tell = '+54' + phoneNumber;
this.FireBase.verifyPhoneNumber(tell, timeOutDuration).then(async (credential) => {
// alert(credential.instantVerification);
if (credential.verificationId) {
console.log("Android credential: ", credential);
verificationId = credential.verificationId;
} else {
console.log("iOS credential: ", credential);
verificationId = credential;
}
if (credential.instantVerification) {
code = credential.code;
this.verifySms(verificationId, code)
.then( resp => {
resolve(resp);
})
.catch( err => {
reject(err);
});
} else {
let prompt = await this.alertCtrl.create({
backdropDismiss: false,
header: 'Ingrese el codigo de confirmación del SMS.',
inputs: [{ name: 'confirmationCode', placeholder: 'Código de confirmación' }],
buttons: [
{ text: 'Cancelar',
handler: data => {
console.log('Cancel clicked');
resolve(data);
}
},
{ text: 'Verificar',
handler: data => {
code = data.confirmationCode;
this.verifySms(verificationId,code)
.then( resp => {
resolve(resp);
})
.catch( err => {
reject(err);
}); }
}
]
});
prompt.present();
}
}).catch(error => {
console.log('Error! Catch SMSVerificacion', error);
reject(error);
});
})
}
verifySms(verificationId, code): Promise <any> {
console.log('parametros de verifySms ', verificationId +' ', code);
const signInCredential = firebase.auth.PhoneAuthProvider.credential(verificationId,code);
return firebase.auth().signInAndRetrieveDataWithCredential(signInCredential);
}
Yes, it's possible to use firebase phone authentication using Cordova plugin,
cordova-plugin-firebase-authentication
Add this plugin to your ionic 4 project
cordova plugin add cordova-plugin-firebase-authentication --save
With this we can verify phone without using reCaptcha.
Note that this only work on real android device, not emulator or browser.
Function implementation
verifyPhoneNumber(phoneNumber, timeout)
cordova.plugins.firebase.auth.verifyPhoneNumber("+123456789", 30000)
.then(function(verificationId) {
// pass verificationId to signInWithVerificationId
});
or
AngularFire (With reCaptcha)
https://github.com/angular/angularfire
First, install angularfire lib into your project
npm install firebase #angular/fire --save
then import this lib into your class
import * as firebase from 'firebase/app';
code example:
firebase.auth().signInWithPhoneNumber(phoneNumber,recaptchaVerifier)
.then(confirmationResult => {
this.windowRef.confirmationResult = confirmationResult;
})