not able to post request from my react native app - node.js

i have created backend server and its working correctly . i did verify it using postman
so i have this as my backend url http://localhost:5000
now i want to store a phone number inside my db.
but it seems that i am not able to establish connection with my backend server
this is the error i am facing
updated error
i am using axios
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:5000',
});
export default instance;
and this is how i am trying to post my data
error is caused when i am trying to connect to my server see from this line
const resp = await lifeApi.post('/signup', { data });
import React, { useState, useEffect } from 'react';
import { TextInput, View, TouchableOpacity, Text } from 'react-native';
import { StyleSheet } from 'react-native';
import auth from '#react-native-firebase/auth';
import lifeApi from '../../api/life';
//const User = require('../../../New folder/aol-backend/src/models/User');
const VerifyOTP = ({ route: { params: { phoneNumber } }, navigation }) => {
// If null, no SMS has been sent
//const [confirm, setConfirm] = useState(true);
const [otp, setOtp] = useState('');
//const [otpArray, setOtpArray] = useState(['', '', '', '']);
const [confirm, setConfirm] = useState(null);
//const User = require('../../../../folder/src/models/User');
useEffect(() => {
signInWithPhoneNumber();
}, []);
async function signInWithPhoneNumber() {
try {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
setConfirm(confirmation);
} catch (e) {
alert(JSON.stringify(e));
}
}
//==========================this is where i am trying to post request ==================================================
async function confirmCode() {
try {
const code = otp;
const response = await confirm.confirm(code);
//================
const data = { phone: response.user._user.phoneNumber };
console.log(JSON.stringify(data));
try {
const resp = await lifeApi.post('/signup', { data });
console.log(resp);
} catch (err) {
console.log(err)
}
//================
console.log(response.user._user.phoneNumber);
navigation.navigate('Home');
} catch (e) {
alert(JSON.stringify(e));
}
}
//=============================================================================
return (
<View>
<TextInput
style={style.display}
value={otp}
onChangeText={text => setOtp(text)}
keyboardType="number-pad"
/>
<TouchableOpacity
onPress={() => {
confirmCode();
}}
>
<Text>
submit
</Text>
</TouchableOpacity>
</View>
);
}
const style = StyleSheet.create({
display: {
borderColor: 'black',
borderWidth: 2,
}
});
export default VerifyOTP;
/**
* if (response) {
await new User({
phone: response.user._user.phoneNumber
}).save();
*/
please if you need any more information on my question , do tell
please help...

Local machine (Laptop/Desktop) in which server application is running and Mobile device should be connected to same network.
Connect your mobile device with Wi-Fi to your local network.
Connect your Laptop also same network. (Server is running in laptop)
Check IP of laptop by running a command in terminal (ifconfig/ipconfig)
Set above IP address in Mobile application Which app you want to test it.
const instance = axios.create({baseURL: 'http://192.168.0.29:5000'}); //IP:Port number

Related

Cookies doesn't show up in my application ReactJS

Hello i'm trying to code auth for my app i'm using json web token the problem is when i send post request using postman i can see the cookie and access token in headers but in my application i can't see anything in my localstorage&cookies
Here is my code
authContext.js
import axios from "axios";
import { createContext, useEffect, useState } from "react";
export const AuthContext = createContext();
export const AuthContextProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(
JSON.parse(localStorage.getItem("user")) || null
);
const login = async (inputs) => {
const res = await axios.post("http://localhost:8800/api/auth/login", inputs, {
withCredentials: true,
});
setCurrentUser(res.data)
};
useEffect(() => {
localStorage.setItem("user", JSON.stringify(currentUser));
console.log(currentUser);
}, [currentUser]);
return (
<AuthContext.Provider value={{ currentUser, login }}>
{children}
</AuthContext.Provider>
);
};
in login.jsx
const [inputs, setInputs] = useState({
username: "",
password: "",
});
const [err, setErr] = useState(null);
const navigate = useNavigate()
const handleChange = (e) => {
setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
};
const login = useContext(AuthContext);
const handleLogin = async (e) => {
e.preventDefault();
try {
await login(inputs);
navigate("/")
} catch (err) {
setErr(err.response.data);
}
};
console.log(err);
console.log(inputs);
I'm trying to solve the problem because i'm trying to create a basic social app i need accessToken to display posts in my feed easily

401 error in axios post request to local server

Context
I'm building a simple web application using the MERN stack for practice. In the app, logged-in users should be able to add a new blog to the site. However, for some reason my axios post request to the backend is failing and I'm receiving a 401 error. I'm using jsonwebtoken to handle the authentication. Submitting a POST request via Insomnia works fine so I don't believe it's an issue with my endpoint. I'm running backend server locally on my machine on port 3003 and have set up a proxy so there's no issues with cors. This works fine as the blogs from the backend are displays on the frontend once a user has logged in.
I've also checked the headers and can confirm that logged-in users have a valid bearer token.
What could be causing the issue?
Frontend
I can't post any images but here's a link to the frontend view:
https://imgur.com/a/DdUlfg9
App.js
import React, { useState, useEffect } from 'react'
import Blog from './components/Blog'
import blogService from './services/blogs'
import loginService from './services/login'
import LoginForm from './components/loginForm'
import BlogForm from './components/blogForm'
const App = () => {
const [blogs, setBlogs] = useState([])
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [user, setUser] = useState(null)
const [errorMessage, setErrorMessage] = useState(null)
const [newBlog, setNewBlog] = useState({
title: '',
author: '',
url: ''
})
useEffect(() => {
blogService.getAll().then(blogs =>
setBlogs( blogs )
)
}, [])
useEffect(() => {
const loggedInUser = window.localStorage.getItem("loggedBlogUser")
if(loggedInUser){
const user = JSON.parse(loggedInUser)
setUser(user)
}
},[])
const handleLogin = async (event) => {
event.preventDefault()
try {
const user = await loginService.login({
username, password
})
window.localStorage.setItem(
'loggedBlogUser', JSON.stringify(user)
)
blogService.setToken(user.token)
setUser(user)
setUsername('')
setPassword('')
} catch (exception){
setErrorMessage('Wrong credentials')
setTimeout(() => {
setErrorMessage(null)
}, 5000)
}
}
const handleLogout = async (event) => {
event.preventDefault()
if(user){
window.localStorage.removeItem("loggedBlogUser")
setUser(null)
}
}
const handleBlogField = (event) => {
event.preventDefault()
const {name, value} = event.target
console.log(newBlog.title)
setNewBlog(prevBlog => ({
...prevBlog,
[name] : value
}))
}
const addBlog = async (event) => {
event.preventDefault()
try {
const blog = await blogService.create(newBlog)
console.log("POST REQUEST: ",newBlog)
console.log('lets geddit')
setBlogs(blogs.concat(blog))
} catch (exception){
setErrorMessage('Uh oh, try again :[')
setTimeout(() => {
setErrorMessage(null)
}, 5000)
}
}
if(user === null){
return(
<>
{errorMessage}
<h2>Log into application</h2>
<LoginForm handleLogin={handleLogin} setUsername={setUsername} setPassword={setPassword} username={username} password={password}/>
</>
)
}
return (
<div>
<h2>blogs</h2>
{user &&
<div>
<h3>{user.username} logged in</h3>
<button onClick={handleLogout}>Logout</button>
</div>
}
<BlogForm handleSubmission={addBlog} newBlog={newBlog} handleBlogField={setNewBlog}/>
{/* <BlogForm addBlog={addBlog} title={newBlog.title} setTitle={setTitle} setAuthor={setAuthor} author={newBlog.author} url={newBlog.url} setUrl={setUrl}/> */}
{blogs.map(blog =>
<Blog key={blog.id} blog={blog} />
)}
</div>
)
}
export default App
Blogs.js
import axios from 'axios'
const baseUrl = '/api/blogs'
let token = null
//let config
const setToken = (newToken) => {
token = `bearer ${newToken}`
}
const getAll = async () => {
const response = await axios.get(baseUrl)
return response.data
}
const create = async (newObject) => {
const config = {
headers: {
Authorization: token
}
}
const response = await axios.post(baseUrl, newObject, config)
console.log(`RESPONSE: ${newObject}`)
return response.data
}
const blogService = {
getAll, setToken, create
}
export default blogService
Have you configured CORS?, in order to accept your localhost requests?

Why axios is not posting data to server for stripe?

Im followin a youtube tutorial to do payments but I am stucked at a pace that axios could not post data to server
code
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Abc from './Abc';
import './index.css'
ReactDOM.render(
<Abc/>
,
document.getElementById('root')
);
Abc.js
import React from "react";
import { loadStripe } from "#stripe/stripe-js";
import {
Elements,
CardElement,
useStripe,
useElements
} from "#stripe/react-stripe-js";
import axios from "axios";
const CheckoutForm = ({ success }) => {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async event => {
event.preventDefault();
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement)
});
if (!error) {
const { id } = paymentMethod;
try {
const { data } = await axios.post("/api/charge", { id, amount: 1099 });
console.log(data);
success();
} catch (error) {
console.log('error is => ',error);
}
}
};
return (
<form
onSubmit={handleSubmit}
style={{ maxWidth: "400px", margin: "0 auto" }}
>
<h2>Price: $10.99 USD</h2>
<img
src="https://images.ricardocuisine.com/services/recipes/500x675_7700.jpg"
style={{ maxWidth: "50px" }}
alt='abc'
/>
<CardElement />
<button type="submit" disabled={!stripe}>
Pay
</button>
</form>
);
};
// you should use env variables here to not commit this
// but it is a public key anyway, so not as sensitive
const stripePromise = loadStripe("pk_test_51JsQsfBbWBJ638dRkTi29yzu85fW6JAvGzbJo9f5RgOtOogcpKnzCfJo6VJoKGemEW54wxrDebWpM8V6vKJl36mC00K3JPAmHr");
const Abc = () => {
const [status, setStatus] = React.useState("ready");
if (status === "success") {
return <div>Congrats on your empanadas!</div>;
}
return (
<Elements stripe={stripePromise}>
<CheckoutForm
success={() => {
setStatus("success");
}}
/>
</Elements>
);
};
export default Abc;
charge.js
import Stripe from "stripe";
const stripe = new Stripe("sk_test_51JsQsfBbWBJ638dRR3Iryb907XNtHaeVYhtCRp6SDmaiWmQg51ys2wdB3z6HJ8svutnA8HPMp5yEtdxTSParn3uN00Xb3PJd4o");
export default async (req, res) => {
const { id, amount } = req.body;
try {
const payment = await stripe.paymentIntents.create({
amount,
currency: "USD",
description: "Delicious empanadas",
payment_method: id,
confirm: true
});
console.log(payment);
return res.status(200).json({
confirm: "abc123"
});
} catch (error) {
console.log(error);
return res.status(400).json({
message: error.message
});
}
};
but this is giving me error when submitting xhr.js:210 POST http://localhost:3000/api/charge 404 (Not Found)
Hierarchy
any help will be appreciated.I was following https://www.youtube.com/watch?v=WTUYem2IxLA&ab_channel=LeighHalliday tutorial
Assuming you have Next.js set up properly, your api folder needs to be in the /pages directory.
https://nextjs.org/docs/api-routes/introduction

I'm fetching dynamic data from my nodejs to reactjs but I get an error saying "POST IS NOT DEFINED"

I have made entries in my mongodb database using node now I'm trying to fetch that data from backend to react front-end the 3rd party app used for cross-platform in node are cors and for react is axios(in script I have added "proxy":"http://localhost:5000"(5000 is my backend port)
Here is my code for NovelCard.js
import React, { Component } from 'react';
import { Container } from 'react-bootstrap';
import Card from 'react-bootstrap/Card';
import axios from 'axios';
const createSet = (post) => {
<Card style={{ width: '18rem' }}>
<Card.Img variant="top" src="holder.js/100px180" />
<Card.Body>
<Card.Title>{post.name}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">{post.author}</Card.Subtitle>
<Card.Text>{post.synopsis}</Card.Text>
</Card.Body>
</Card>;
};
class Latest extends Component {
state = {
name: '',
author: '',
synopsis: '',
post: [],
};
componentDidMount = () => {
this.getData();
};
getData = () => {
axios
.get('http://localhost:5000/novels/')
.then((res) => {
const data = res.data;
this.setState({ post: data });
console.log('data recived');
})
.catch(() => {
alert('error');
});
};
render() {
console.log('state', this.state);
return <Container>{post.map(createSet)}</Container>;
}
}
export default Latest;
I'm getting error saying ***
src\components\home\Latest\NovelCard.js Line 45:24: 'post' is not
defined no-undef
Your post variable is available within you state. You need to do something like this within your render function.
render() {
console.log('state', this.state);
return <Container>{this.state.post.map(createSet)}</Container>;
}
Or you can do like this as well.
render() {
const { post } = this.state;
console.log('state', this.state);
return <Container>{post.map(createSet)}</Container>;
}

I get the path of the image displayed on my react app instead of the actual image and on my react-native app the images don't get displayed at all

Question number 1: I've created a CRUD (CMS) app with react where you create articles. My backend is in node.js and my DB is in MySQL. I also have a react-native app that pulls all the articles I created on my CMS. Where do I store the images I add to my articles? In a folder in my backend? Or somewhere else?
Question number 2: So I've connected to my db and I'm displaying on my CMS react web page the title, content and image. And yet when it comes to the image, you can only see the path ie. (C:\fakepath\Screenshot 2020-06-14 at 23.07.52.png), not the actual image. I don't know if the issue is with my backend but after a bit of online research a lot of people said that you need to add require in the src if you want the actual image displayed and not just the path, a bit like this:
<img src={require('./logo.jpeg')} />
However with the way I've done it I don't see how I can use the img tag and add src because I'm fetching image to render from the backend and hence, not creating the img tag. Hope this makes sense.
ViewAllArticles.js
class ViewAllArticles extends Component {
state = {
articles: []
}
getArticles = _ => {
fetch('http://localhost:4000/articles')
.then(response => response.json())
.then(response => this.setState({ articles: response.data }))
.catch(err => console.error(err))
}
componentDidMount() {
this.getArticles();
}
renderArticle = ({ id, title, image }) => <div key={id}>{title}, {image}</div>
render() {
const { articles } = this.state;
return (
<div>
<h1>Home</h1>
<div>
{articles.map(this.renderArticle)}
</div>
</div>
);
}
}
export default ViewAllArticles;
If the require is not what's missing do you have any other ideas of why this is happening?
I'm also pulling the same data for my react-native app and the images don't come up.
This is the code in my react-native app:
largeTitle={item.title} works fine and displays all the titles on the cards but source={item.image} doesn't display the images on the same cards.
HomeFeed.js
import React, { Component } from "react";
import { StyleSheet, Text, View, FlatList } from 'react-native';
import {AppleCard, AppOfTheDayCard} from 'react-native-apple-card-views';
export default class HomeFeed extends Component {
constructor() {
super()
this.state = {
dataSource: []
}
}
// https://github.com/WrathChaos/react-native-apple-card-views
renderItem = ({ item }) => {
return (
<View>
<View style={styles.card}>
<AppleCard
largeTitle={item.title}
footnoteText="subtitle placeholder"
source={item.image}
>
</AppleCard>
</View>
</View>
)
}
componentDidMount() {
const url = 'http://localhost:4000/articles'
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.data
})
})
}
render() {
return(
<View style={styles.homeFeed}>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
/>
</View>
);
}
}
const styles = StyleSheet.create({
homeFeed: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
},
card: {
padding: 15
}
});
This is my backend code in node.js
index.js
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const { query } = require('express');
const multer = require('multer');
const upload = multer({dest: 'public/images'}); // uploaded article image here
const app = express();
//all queries go here
const SELECT_ALL_ARTICLES_QUERY = 'SELECT * FROM articles';
//create connection
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'DidiLydiBibi96',
database: 'myTherapy'
});
connection.connect(err => {
if(err) {
return err;
}
});
//end of creating connection
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /articles to see articles')
});
//ROUTES
//Add new article
app.use('/image', express.static('public/images'));
app.get('/articles/add', upload.single('image'), (req, res) => {
const { title, content, image } = req.query; //fields from db
const INSERT_ARTICLES_QUERY = `INSERT INTO articles (title, content, image) VALUES(?, ?, ?)`;
connection.query(INSERT_ARTICLES_QUERY, [title, content, image], (err, results) => {
if(err) {
return res.send(err)
}
else {
return res.send('successfully added article')
}
});
});
//View all articles
app.get('/articles', (req, res) => {
connection.query(SELECT_ALL_ARTICLES_QUERY, (err, results) => {
if(err) {
return res.send(err)
}
else {
return res.json({
data: results
})
}
});
});
app.listen(4000, () => {
console.log('Articles server listening on port 4000')
});
For the first problem, getting the image uri from the server is good enough, and it's your react application that should handle converting that to a visible image.
One way to do this would be to change your renderArticles method like :
renderArticle = ({ id, title, image }) => (
<div key={id}>
{title}
<div
style={{
width: "100px",
height: "100px",
backgroundSize: "cover",
backgroundImage: "url(" + image + ")"
}}
></div>
</div>
);

Resources