i have imported laravel-echo and #pusher/pusher-websocket-react-native in react native but error occur:can not find variable pusher
please tell me solution will be thankfully
import Echo from "laravel-echo";
import {
Pusher,
PusherMember,
PusherChannel,
PusherEvent,
} from '#pusher/pusher-websocket-react-native';
let echo = new Echo({
broadcaster: "pusher",
key: "123",
wsHost: "my-domain",
wsPort: 6001,
forceTLS: false,
cluster: "mt1",
disableStats: true,
authorizer: (channel, options) => {
console.log(options);
return {
authorize: async (socketId, callback) => {
console.log('socketId, callback',channel,socketId, callback)
const response = await fetch(`http://my-domain/api/broadcasting/auth`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
ContentType: 'application/json'
},
data: {
socket_id: socketId,
channel_name: channel.name,
},
})
.then((response) => {
console.log('fd',response);
callback(false, response.data);
})
.catch((error) => {
console.log('test',error)
callback(true, error);
});
},
};
},
});
=============================================================================================================================================
You must define Pusher to window
window.Pusher = Pusher;
Just write this line below the import
Related
Upload file with axios , graphql and formdata##
I want to upload image in the nodejs server by graphql and formdata with axios and this is my way but not working , I think this problem is in append to form data but I can not find why or in axios fetch data
Code
let data = {
query: `
mutation Mutation($image: Upload!) {
multimedia(image: $image) {
status
message
token
}
}`,
variables: {
image: null,
},
};
let map = {
0: ["variables.image"],
};
const FormD = new FormData();
FormD.append("operation", JSON.stringify(data));
FormD.append("map", JSON.stringify(map));
FormD.append(0, element.file, element.file.name);
console.log(FormD);
await axios({
url: "/",
method: "POST",
headers: {
token: token,
"Content-Type": "multipart/form-data",
},
data: FormD,
onUploadProgress:ProgressEvent=>{
element.loaded=ProgressEvent.loaded/ProgressEvent.total*100
}
})
.then((response) => {
if (response.data.errors) {
const { message } = response.data.errors[0];
toast.error(message);
} else {
setLoadedFiles(tempLoadedFiles);
}
})
.catch((error) => {
console.log(error);
});
but the response is
response
{
"message": "Request failed with status code 400",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZjY3NWZiODkwNjY0N2RlZWRmMTM5ZiIsImlhdCI6MTY2MDg5NTgzMSwiZXhwIjoxNjYzNDg3ODMxfQ._5gmsMHD_HRokvoopKOit1n8YhG_sP3oR_OLRSXqZTo"
},
"baseURL": "http://localhost:4000/graphql",
"url": "/",
"method": "post",
"data": {}
},
"code": "ERR_BAD_REQUEST",
"status": 400
}
thanks for your answer
I fixed this issue ,
dont use
let data = {
query: `
mutation Mutation($image: Upload!) {
multimedia(image: $image) {
status
message
token
}
}`,
variables: {
image: null,
},
};
and replace it in the axios
await axios({
url: "/",
method: "post",
headers: {
"token": token,
"Content-Type": "application/json",
},
data: {
query: `
mutation Mutation( $image : Upload!) {
multimedia(image: $image) {
status
message
}
}`,
variables: {
image: element.file,
},},
onUploadProgress: (ProgressEvent) => {
tempLoadedFiles[index].loaded =
(ProgressEvent.loaded / ProgressEvent.total) * 100;
},
})
and it's working...
this problem solve in the nodejs server
fixed it in server by:
import express from "express";
import mongoose from "mongoose";
import Router from "./routes/index.js";
import User from "./models/users.js";
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import { ApolloServer } from "apollo-server-express";
import MakeSchema from "../api/models/index.js";
import { config } from "../config/index.js";
const app = express();
const Application = () => {
const ServerConfig = async () => {
const server = new ApolloServer({
schema: MakeSchema,
playground: true,
introspection: "production",
formatError(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const code = err.originalError.code || 500;
const message = err.message || "error";
return { message, data, code };
},
context: async ({ req }) => {
let check;
let user;
let userInfo;
await User.VerifyToken(req).then((val) => {
check = val;
});
if (check) {
user = await User.findById(check.id);
userInfo = await User.CheckUserInfo({
fname: user.fname,
address: user.address,
});
}
if (user) {
return { role: user.role, check, userInfo };
}
return { check, role: user };
},
});
await server.start();
**app.use(graphqlUploadExpress())
app.use(express.static('public'))
app.use('/public',express.static('public'))
await server.applyMiddleware({ app });**
app.listen(config.port, () => {
console.log(`Server run on port ${config.port}`);
});
};
const DatabaseConfig = () => {
mongoose.Promise = global.Promise;
mongoose.connect(config.database.url, config.database.options);
};
const Routes=()=>{
app.use(Router)
}
ServerConfig();
DatabaseConfig();
Routes();
};
export default Application;
$Happy New Year! So, I'm setting up a redirect after an authentication token retrieval and I keep getting "TypeError: Cannot read properties of undefined (reading '$router')" in the console and the user is not redirected to the desired page ("/dashboard"). I'm outsourcing the authentication to a dataRequests.user.js file that then goes to a vue component. Thanks in advance. Here is the code:
import common from "./dataRequests.commons";
import { login, inputLogin, inputPassword } from '/src/pages/Index.vue'
let userRequest = {}
userRequest.authenticate = (inputLogin, inputPassword) => {
return new Promise(() => {
let axios = require("axios");
let config = {
method: 'post',
baseURL: common.baseURL + '/auth/login',
headers: {
'Content-Type': 'application/json',
},
data : {
login: inputLogin,
password: inputPassword,
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(() => this.$router.push(this.$router.redirect || '/dashboard'))
.catch(function (error) {
console.log(error);
//console.log('input login', this.inputLogin)
//console.log('input password', this.inputPassword)
});
console.log('input login', inputLogin)
console.log('input password', inputPassword)
});
}
export default userRequest;
Something like this:
import common from "./dataRequests.commons";
import { login, inputLogin, inputPassword } from '/src/pages/Index.vue'
import axios from 'axios'
import router from 'router'
let config = {
method: 'post',
baseURL: common.baseURL + '/auth/login',
headers: {
'Content-Type': 'application/json',
}
userRequest.authenticate = (inputLogin, inputPassword) => {
const apiClient = axios.create(config)
return new Promise(() => {
apiClient.post(data : {
login: inputLogin,
password: inputPassword,
})
.then(() => router.push...etc
I am using ApolloClient to send mutation that contains files (images) but I am getting
Error: Network request failed
this what I have done to create links
import { createUploadLink } from 'apollo-upload-client' v ==>> "^15.0.0";
const uploadLink = createUploadLink({
uri: API_URL,
headers: {
"Authorization": `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
"Accept":"application/json"
},
});
this to handle errors
import { onError } from "#apollo/client/link/error"; v ==>> "^3.3.20"
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network zaid error]: ${networkError}`);
});
then :
const client = new ApolloClient({
cache: new InMemoryCache(),
link: from([errorLink,uploadLink]),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'none'
},
mutate: {
mutation: "DocumentNode",
errorPolicy: 'none'
},
},
});
then I called the mutation :
await client.mutate({
mutation:
gql`
mutation($data: PostCreatInput!, $files: [CustomCreateImages!]!) {
createpost(data: $data, files: $files) {
id
}}`,
variables: {
data: {****},
files:[{file:ReactNativeFile}]
}
}).then(response => {
console.log(response);
return response
}).catch(response => {
console.log(response);
return response
})
i used ReactNativeFile generated by apollo-upload-client
new ReactNativeFile({
uri: "file:///storage/***.jpg",
name: "a.jpg",
type: "image/jpeg"
});
I am using react native "react-native": "0.62.2"
and I have a live server not using localhost
I did check the server logs this request never left the mobile; there was no record of it on the server.
been stuck all day on it, any help would be highly appreciated!
bug with React Native 0.62+ that messes up the configuration for multiform requests. It can be fixed by commenting out line 43 in android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java:
//builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
I am trying to integrate stripe payment gateway. I have a nuxt.js for front-end and adonis.js for backend.
From front-end I am calling an api to backend to create checkoutSession and return the sessionID. I am able to create checkoutSession and return the sessionID and in api response I am calling the
stripe.redirectToCheckout but it is not redirecting rather gives error as stripe.redirectToCheckout is not a function. How can I redirect users to checkout Page?
I have install the stripe-js file also.
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
<button class="btn btn-primary btn-block text-center rounded" #click="checkout()">Buy</button>
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
export default {
methods: {
checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
}
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then((response) => {
this.stripeSession = response.data.data
stripe.redirectToCheckout({sessionId: this.stripeSession})
})
.catch((e) => {
console.log(e)
})
}
},
}
</script>
According to tyhe doc, loadStripe is an async function, try adding await in stripe assignement:
const stripe = await loadStripe(process.env.STRIPE_PK)
Edit:
To get rid of Module parse failed: Cannot use keyword 'await' outside an async function error you just need to add async before your function declaration :
async function myAsyncFunction() {
const test = await myPromise();
}
As I do not have the full definition of your function I cannot show it to you in your code :-(
But a weird solution (mixing 'await' and 'then') would be :
import { loadStripe } from '#stripe/stripe-js';
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then(async response => {
this.stripeSession = response.data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
})
.catch(e => {
console.log(e);
});
This should work:
import { loadStripe } from '#stripe/stripe-js';
export default {
methods: {
async checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
};
try {
const { data } = await axios.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
});
this.stripeSession = data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
} catch (error) {
console.error(error);
}
},
},
};
I tried to call APP with this code imported from another file and it worked fine:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
let formData = new FormData();
formData.append('userId', '1'); // < this is what I want to change
formData.append('key', '***'); //my key
export function getScoreFromAPI () {
return fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
}
but now I want to change my userId from 1 to an constante from Asyncstorage, so I decide to change my code to this:
constructor(props) {
super(props)
this.state = { infos: [], userId: '' }
}
componentWillMount() {
this.getScoreFromAPI().then(data => {
this.setState({ infos: data })
});
console.log(this.state.infos);
AsyncStorage.getItem(USERID_STORED)
.then((data) => {
if (data) {
this.setState({userId:data})
}
});
}
async getScoreFromAPI() {
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
try {
let response = await fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
let res = await response.json();
} catch(error) {
console.warn("errors are " + error);
}
};
with a try-catch function but when I call getScoreFromAPI() in ComponentWillMount() I can't setState with received data, I still have an empty array in info:[]
my questions:
how can I replace '1' in userId by a value in asyncstorage in the first file ?
if it isn't possible, what I have do to setState info: [] with my data reveived
I've simplified your code into a promise chain in which calling getScoreFromAPI will execute after getting the userId from AsyncStorage, then storing the response into the infos state, while returning null if there was an error, and logging the error to the console. The data was not previously returned from getScoreFromAPI, so the value would always become null. I have not tested this code, but this should give you a good base to work from:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
export default class Test {
constructor() {
this.state = {
infos: null,
userId: ''
};
}
componentDidMount() {
AsyncStorage.getItem(this.state.userId)
.then(userID => {
this.setState({ userId: userID || '' });
})
.then(() => {
return this.getScoreFromAPI();
})
.then(data => {
this.setState({ infos: data });
})
.catch(console.error);
}
getScoreFromAPI = () => {
const formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(response => {
// use response data here
return response.json();
})
.catch(e => {
console.error(e);
return null;
});
};
}
You're doing your API call before fetching your value from AsyncStorage (I know this is async but it's not very readable if you do it that way).
getScoreFromAPI doesn't return anything, that's why your setState isn't working.
You don't need to use try and catch here, promises have their own error handling mechanism (the .catch() method).
I think callbacks are more readable and lead to less bugs than using .then() in code.
This is how I would do it:
constructor(props)
{
super(props);
this.state = { infos: [], userId: '' };
this.onSuccess = this.onSuccess.bind(this);
this.onFailure = this.onFailure.bind(this);
}
componentWillMount()
{
// Get userID from local storage, then call your API
AsyncStorage.getItem(YOUR_KEY)
.then(userID=> {
if (userID)
{
this.setState({ userId : userID }, () => {
this.getScoreFromAPI(this.onSuccess, this.onFailure);
});
}
});
}
onSuccess(data)
{
this.setState({
infos : data
});
}
onFailure(err)
{
console.warn('Error ' + err);
}
getScoreFromAPI(onSuccess, onFailure)
{
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //your key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(res => res.json())
.then(json => {
onSuccess(json);
})
.catch(err => {
onFailure(err);
});
}
It's finally done. I tried this and it worked. Thank you to all of you
this is what I have done:
...
const USERID_STORED = "userid_stored";
const GSM_STORED = "gsm_stored";
...
class ScoreList extends React.Component {
constructor(props) {
super(props)
this.state = { infos: [], userId: '', gsmStored: '', }
}
componentWillMount() {
AsyncStorage.getItem(USERID_STORED)
.then(userId => {
this.setState({ userId: userId});
this.getScoreFromAPI(this.state.userId).then(data => {
this.setState({ infos: data });
});
});
AsyncStorage.getItem(GSM_STORED)
.then(gsmStore => {
this.setState({ gsmStored: gsmStore});
});
}
getScoreFromAPI (userId) {
let formData = new FormData();
formData.append('userId', userId);
formData.append('key', '***');
return fetch('https://***',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
};