react native error
import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true
};
}
async getMovies() {
try {
const response = await fetch('http://192.168.1.6:80/p4Lite/Sept2021/react_backend/index.php');
const json = await response.json();
this.setState({ data: json });
} catch (error) {
console.log(error);
} finally {
this.setState({ isLoading: false });
}
}
componentDidMount() {
this.getMovies();
}
render() {
const { data, isLoading } = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.name}, {item.email}</Text>
)}
/>
)}
</View>
);
}
};
Above is my app.js file code. It works fine on web but shows error on my android phone using expo go. I have tried various methods but till now is solution fond. I am working on localhost.
Try this on your API related folder
sudo chmod -R -f 777 /path/to/your/file/or/directory
the 403 error means that the request you made was forbidden. it is generally received when a required password is not entered.
Most likely, your API requires a password, and this was not provided by the code, the server code is miss-configured, or the server does not have the right permissions to display the result.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403
Some how it's working by changing:
Require local to Require all granted in httpd-vhosts.conf
Related
I made login with PHP and React Native but now I want to display the ID of the user that's logged in. The ID should be showed on the screen that appears when the user is logged in.
I tried several things but I think the way I request the props is wrong. Because the page where I want to show never requests the data that is started in the previous page.
This is the login screen:
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import * as Expo from 'expo';
export default class App extends React.Component {
state = {
username: '',
password: '',
response: '',
users_ID: '',
};
handleusers_usernameChange = (users_username) => {
this.setState({ users_username });
};
handleusers_passwordChange = (users_password) => {
this.setState({ users_password });
};
handleLoginPress = async () => {
const { users_username, users_password } = this.state;
try {
let response = await fetch('http://IP/CodingApp/login.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
users_username,
users_password,
}),
});
let responseJson = await response.json();
console.log(responseJson);
if (responseJson.loggedin) {
this.props.setLoggedIn(true, responseJson.users_ID);
this.setState({ users_ID: responseJson.users_ID });
} else {
this.setState({ response: 'tekst kwam niet overeen' });
}
} catch (error) {
console.error(error);
}
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
value={this.state.users_username}
onChangeText={this.handleusers_usernameChange}
placeholder="users_username"
/>
<TextInput
style={styles.input}
value={this.state.users_password}
onChangeText={this.handleusers_passwordChange}
placeholder="users_password"
secureTextEntry
/>
<Button title="Login" onPress={this.handleLoginPress} />
<Text>{this.state.response}</Text>
</View>
);
}
}
And this is the screen that appears after the user is logged in:
import React from 'react';
import { View, Text } from 'react-native';
const EditFamily = (props) => {
return (
<View>
<Text>Your user ID is: {props.users_ID}</Text>
</View>
);
};
export default EditFamily;
Read about redux, which is a state management tool, you can save id whenever or wherever you go and use it everywhere.
https://redux.js.org/introduction/getting-started
I have a problem when making an axios request, it returns a 404 error, the file path is fine since it is in the same directory and I do not understand why it returns that error,
I am using vue-cli, and I run the server with npm run serve instead of express.
Register.vue
var formData = new FormData();
formData.append("nombre", nombre);
formData.append("mail", mail);
formData.append("pass", pass);
axios
.post("./auth_register.php", formData)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
auth_register.php
<?php
if (isset($_POST['nombre']) && $_POST['mail'] && $_POST['pass']) {
return json_encode("received");
} else {
return null;
}
I don't know why this happens
I am new to vue do not be angry
Try using the full path; Worked for me! after long searching
example -> http://localhost:8080/api/authentication/login.php
i want to send the Google Recaptcha V3 to WP Rest API using Contact Form 7.
This is what i have done so far:
I just use WP as BackEnd API provider, my frontend is in Nuxt app - full static generated code
Wordpress
Install Contact Form 7 plugin
Configured the Google Recaptcha V3 Site Key and Private Key
Create a specific form form my Nuxt App
Test the form in a Wordpress test page and it works fine
Nuxt
Install #nuxtjs/recaptcha
Insert in .env the site key and api URL of contact form
in nuxt.config.js
publicRuntimeConfig: {
contactFormApi: process.env.CONTACT_FORM_API,
// other staff
},
modules: [
['#nuxtjs/recaptcha', {
hideBadge: true
,siteKey: process.env.RECAPTCHA_SITE_KEY
,version: 3
}],
// other staff
],
in layout/default.vue:
async mounted() {
try {
await this.$recaptcha.init()
} catch (e) {
console.log(e);
}
},
beforeDestroy () {
this.$recaptcha.destroy();
// other staff
}
contact form component:
<template>
<form role="form">
<v-text-field v-model="email" name="email" :label="$t('form.yourEmail')" autocomplete="email" :placeholder="$t('form.yourEmailHint')" clearable
></v-text-field>
<v-textarea v-model="message" name="message" :label="$t('form.yourMessage')" rows="3" value="" :hint="$t('form.yourMessageHint')" clearable
></v-textarea>
<v-checkbox v-model="acceptPrivacy" :label="$t('form.acceptPrivacyTerms')"></v-checkbox>
<v-btn #click="submit">{{ $t('btns.send') }}</v-btn>
</form>
</template>
<script>
export default {
data: () => ({
email: '',
message: '',
acceptPrivacy: false,
}),
methods: {
async submit() {
if (!this.acceptPrivacy || this.email == '' || this.message == '') {
return false;
}
try {
const token = await this.$recaptcha.execute('login');
console.log('ReCaptcha token:', token);
const emailBody = {
"_wpcf7_recaptcha_response" : token,
"wpcf7_recaptcha_response" : token,
"recaptcha_response" : token,
"recaptcha" : token,
"token" : token,
"email": this.email,
"message" : this.message,
"privacy_terms" : this.acceptPrivacy? 1 : 0
};
const form = new FormData();
for (const field in emailBody) {
form.append(field, emailBody[field]);
};
const headers = {
'Content-Type': 'multipart/form-data',
};
const data = await this.$axios.$post(
this.$config.contactFormApi,
form,
{ headers: headers }
);
if (data == null || data == undefined || data.status !== 'spam') {
console.log('Email has NOT been sent');
console.log(data);
return;
}
console.log('Email has been sent');
console.log(data);
} catch (error) {
console.log('Login error:', error)
}
}
}
}
</script>
I try to send the email from my localhost:3000, the other API of WP in order to get pages, post, customPostTypes work as expected.
After every request to WPCF7 i get this response:
{
"into": "#",
"status": "spam",
"message": "There was an error trying to send your message. Please try again later.",
"posted_data_hash": ""
}
As you can see in the request i don't know the proper way to send the gRecaptcha token that i correctly get from google service response:
"_wpcf7_recaptcha_response" : token,
"wpcf7_recaptcha_response" : token,
"recaptcha_response" : token,
"recaptcha" : token,
"token" : token,
Can you help me for this issue?
Thanks in advance
I try to pass my project create on linux to a windows but i got a problem.
In my project i got a DB and all is fine, i can sign in and in my table i see my account.
Now my login function in auth.js (store)
async login({ dispatch }, credentials){
let response = await axios.post(`/api/auth/connexion`, credentials);
if(!response.data.error){
dispatch('attempt', response.data.token).then((resp)=> {
if(resp){
dispatch('message/resetState', null , {root: true});
router.push({ name: 'Home', query: {category: 'home'} });
}
});
}else {
dispatch('message/setError', response.data.error , {root: true});
}
}
And my dispatch('attempt', response.data.token) ;
async attempt({ commit, state }, token) {
if(token){
commit('SET_TOKEN', token);
}
if (!state.token){
return
}
try{
let response = await axios.get(`/api/auth/me`);
commit('SET_USER', response.data);
response = await axios.get(`/api/auth/isAdmin`);
commit('SET_ADMIN', response.data);
return true;
}
catch(err){
commit('SET_TOKEN', null);
commit('SET_USER', null);
commit('SET_ADMIN', null);
}
}
If i console.log token in is printed, but ir the :
await axios.get(`/api/auth/me`)
Don't works and i found why, it's because my method login and signin is in except middleware :
$this->middleware('auth:api', ['except' => ['login', 'register']]);
My question is :
Why my auth middleware is not setup and not work ??
This project work fine on my other pc on linux.
Thanks for help !
I have a problem following this tutorial to implement a simple chat in Laravel using Pusher and Vue.js: link tutorial.
First of all my route in the navbar is this one:
http://localhost/youChat/public/
My web.php file contents the following routes:
Auth::routes();
Route::get('/', 'TweetController#index');
Route::get('tweets', 'TweetController#showTweets')->middleware('auth');
Route::post('tweets', 'TweetController#sentTweet')->middleware('auth');
My app.js file in assets/js where I make the request is this one:
const app = new Vue({
el: '#app',
data: {
tweets: []
},
created() {
this.showTweets();
Echo.private('chat')
.listen('TweetSentEvent', (e) => {
this.tweets.push({
tweet: e.tweet.tweet,
user: e.user
});
});
},
methods: {
showTweets() {
axios.get('/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('/tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
});
As you can see I send the request with Axios.
Everything seems looks fine but the GET and POST request are not working. The error in the console inspector shows this:
GET http://localhost/tweets 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:13931)
at settle (app.js:35401)
at XMLHttpRequest.handleLoad (app.js:13805)
GET https://stats.pusher.com/timeline/v2/jsonp/1session=Njg3NjQyNDY5NT....MjY1fV0%3D 0 ()
POST http://localhost/broadcasting/auth 404 (Not Found)
And when I try to make a POST:
POST http://localhost/tweets 404 (Not Found)
The get/post should go to this direction:
http://localhost/youChat/public/tweets
but I don't know what's happening. Any suggestion? I'm desperated :D.
Thanks in advance!
You are getting this error because you are using an absolute path.
So either you can store the Base url in a variable or you can use relative path
here is an example.
methods: {
showTweets() {
axios.get('tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Remove the / before the URL or
save a
const URL = '{{url('/')}}'
methods: {
showTweets() {
axios.get(URL + '/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post(URL + '/tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Hope this helps