I have a problem with axios Post. I work on adding Stripe payment to my page, but i send me axios error 404.
Maybe somebody can help me, I stuck on it for week already and cant just solve it.
Here is the code:
import React from 'react'
import StripeCheckout from 'react-stripe-checkout';
import { useState, useEffect } from "react";
import { useNavigate } from 'react-router-dom';
import axios from "axios";
const Pay = () => {
const [stripeToken, setStripeToken] = useState(null)
const navigate = useNavigate()
const onToken = (token) => {
setStripeToken(token);
}
useEffect(() => {
const makeRequest = async () => {
try {
const res = await axios.post(
"http//:localhost:5001/api/checkout/payment",
{
tokenId: stripeToken.id,
amount: 6000,
});
console.log(res.data)
} catch (err) {
console.log(err)
}
};
stripeToken && makeRequest()
}, [stripeToken]);
return (
<div className='pay__div'>
{stripeToken ? (<span>Processing</span>) : (
<StripeCheckout
name="Kate store"
image=""
billingAddress
shippingAddress
description="Yout total is $60"
amount={2000}
token={onToken}
stripeKey={KEY}
>
<button>Pay</button>
</StripeCheckout>
)}
</div>
)
}
export default Pay
Thank you for your time.
Also here are stripe.js index.js pages from backend
stripe.js
const router = require("express").Router();
const stripe = require("stripe")(process.env.STRIPE_KEY);
router.post("/payment", (req, res) => {
stripe.charges.create({
sourse: req.body.tokenId,
amount: req.body.amount,
currency: "usd"
},
(stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).json(stripeErr);
} else {
res.status(200).json(stripeRes);
}
});
});
module.exports = router;
And index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");
const stripeRoute = require("./routes/stripe");
const cors = require("cors");
dotenv.config();
mongoose.connect(process.env.MONGO_URL)
.then(() => console.log("DB Connected Successfull!"))
.catch((err) => {
console.log(err);
})
app.use(cors());
app.use(express.json());
app.use("/api/user", userRoute);
app.use("/api/auth", authRoute);
app.use("/api/product", productRoute);
app.use("/api/cart", cartRoute);
app.use("/api/order", orderRoute);
app.use("/api/checkout", stripeRoute);
app.listen(process.env.PORT || 5001, () => {
console.log("Backend is running")
})
Had the same problem. Moved dotenv.config(); before const stripeRoute = require("./routes/stripe"); in index.js and worked.
Related
topbar.vue
<script setup>
import { ref, computed, onMounted, onBeforeUnmount ,reactive} from 'vue';
import { useLayout } from '#/layout/composables/layout';
import { useRouter } from 'vue-router';
import ApiService from '../services/api.service';
const { layoutConfig, onMenuToggle, contextPath } = useLayout();
//const state = ref(null);
const outsideClickListener = ref(null);
const topbarMenuActive = ref(false);
const router = useRouter();
const items =[];
const dropdownItems = ref(items);
const dropdownItem = ref(null);
onMounted(() => {
ApiService.getStores().then((data) => {
data.forEach((value) => {
items.push({ name: value.shop,value:value.id });
});
});
});
const onSelectChange = () => {
localStorage.setItem('shop-id',dropdownItem.value);
//console.log(dropdownItem.value);
}
</script>
<Dropdown id="state" v-model="dropdownItem" :options="dropdownItems" :filter="true"
optionLabel="name" optionValue="value" #change="onSelectChange()"></Dropdown>
api.service
async getProduct() {
if(!shop)
{
return axios.get(API_URL+'/product/all?id=1', { headers: authHeader() })
.then((res) => res.data);
}
else{
return axios.get(API_URL+'/product/all?id='+shop, { headers: authHeader() })
.then((res) => res.data);
}
}
here dropdown selcted value to id set localstorage after pass axios services api its working fine only
when i page refresh.
but i want to without page refresh dropdown selected value to get data form api.
how to solve this?
Let me start by saying I see other answered questions with this a similar title but nothing is working for me.
I'm trying to get the users Birthday from Facebooks API, I'm using expo-auth-session.
I can successfully get the users ID, email and name but nothing else.
Here is my code, what am I missing?
const [request, response, promptAsync] = Facebook.useAuthRequest({
// clientId: '2877415105738397',
androidClientId: FacebookClientId,
iosClientId: FacebookClientId,
expoClientId: FacebookClientId,
scopes: ['user_birthday '],
redirectUri: makeRedirectUri({ useProxy: true })
});
Once I have the access_token
await axios.get(`https://graph.facebook.com/v15.0/me?fields=id,name,email,birthday&access_token=${token}`)
But I only get the {"email": "email#gmail.com", "id": "123415656565", "name": "Name"}
I do have app review permissions
UPDATE, FULL COMPONENT BELOW
import * as React from 'react';
import { View } from 'react-native';
import * as AppAuth from 'expo-auth-session';
import { useAuthRequest } from 'expo-auth-session/build/providers/Facebook';
import { FacebookClientId } from '../config/constant';
import { TouchableOpacity } from 'react-native';
import { FacebookIcon } from '../assets/SvgIcons/FacebookIcon';
import { Styling } from '../assets/style/styling';
import { useEffect, useState } from 'react';
import { onSignupExternal } from '../store/user/user.action';
import { useNavigation } from '#react-navigation/core';
import { useDispatch, useSelector } from 'react-redux';
const useProxy = Platform.select({ web: false, default: true, 'android': true, 'ios': true });
const discovery = {
authorizationEndpoint: 'https://www.facebook.com/v6.0/dialog/oauth',
tokenEndpoint: 'https://graph.facebook.com/v6.0/oauth/access_token',
};
export const FaceBook = ({ setLoading }) => {
const [userData, setUserData] = useState({})
const navigation = useNavigation()
const dispatch = useDispatch();
const { user } = useSelector((storeState) => storeState.userModule);
const clientId = FacebookClientId;
const scopes = ['public_profile', 'email', 'user_birthday'];
const [request, response, promptAsync] = useAuthRequest(
{
clientId,
scopes,
useProxy,
redirectUri: AppAuth.makeRedirectUri({
native: 'com.myapp.app:/',
useProxy,
}),
},
{useProxy: useProxy},
discovery
);
async function handlePress() {
try {
const result = await promptAsync();
if (result.type === 'success') {
setLoading(true)
getUserData(result.params.access_token)
} else {
// The user cancelled the login or an error occurred. You can inspect the result object for more details.
console.log('Login failed :(', result);
}
} catch (e) {
console.error(e);
}
}
async function getUserData(token) {
let response = await fetch(`https://graph.facebook.com/me?fields=id,name,email,birthday&access_token=${token}`);
const userInfo = await response.json()
console.log(userInfo)
setUserData({
user_email: userInfo.email,
user_id: userInfo.id,
user_full_name: userInfo.name,
user_ref_id: null,
auth_system: 'Facebook',
user_dob: null
})
}
useEffect(() => {
const getUser = async () => {
let updateUserData = userData
// let ref_id = await utilService.convertMailToAsciiCode(userData.user_id)
// updateUserData.user_ref_id = ref_id
return Object.keys(userData).length !== 0 && dispatch(onSignupExternal(userData))
};
getUser()
}, [userData])
useEffect(() => {
if (user !== null && user?.user_id !== undefined) {
setLoading(false)
return navigation.navigate("Dashboard")
}
}, [user])
return (
<TouchableOpacity style={Styling.facebookLoginBtn}
onPress={handlePress}>
<View style={Styling.googleIcon}><FacebookIcon /></View>
</TouchableOpacity>
)
}
I am trying to establish a peer-to-peer video connection between a web frontend and a react-native android smart tv app. I want to display the user's webcam video on the smart tv. I am using an express server for signaling:
const app = require("express")();
const server = require("http").createServer(app);
const cors = require("cors");
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: [ "GET", "POST" ]
}
});
app.use(cors());
const PORT = process.env.PORT || 8082;
//here we define the behaviour of the API Endpoints
app.get('/', (req, res) => {
res.send('Runnin');
});
app.post('/',(req,res) => {
const body = req.body;
res.send(body);
});
io.on("connection", (socket) => {
socket.emit("me", socket.id);
console.log(socket.id);
socket.on("disconnect", () => {
socket.broadcast.emit("callEnded")
});
socket.on("callUser", ({ userToCall, signalData, from, name }) => {
io.to(userToCall).emit("callUser", { signal: signalData, from, name });
});
socket.on("answerCall", (data) => {
io.to(data.to).emit("callAccepted", data.signal)
});
});
server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
The signaling is working but as I am trying to display the video the following error is displayed:
[Link to screenshot of the error][1]
Code of the react-native Callscreen component:
import React, { useEffect, useState, useCallback, useContext } from 'react';
import { View, StyleSheet, Alert, Button, Text } from 'react-native';
import { RTCView } from 'react-native-webrtc';
import { SocketContext } from './Context';
import Callnotification from './Callnotifcation';
function CallScreen(props) {
const { callAccepted, userVideo, callEnded, me } = useContext(SocketContext);
return (
<>
{callAccepted && !callEnded && (
<View style={styles.root}>
<View style={[styles.videos, styles.remoteVideos]}>
<Text>Video of the caller</Text>
<RTCView streamURL={JSON.stringify(userVideo)} style={styles.remoteVideo} />
</View>
</View>
)
}
<View style={styles.root}>
<Callnotification />
<Text>{JSON.stringify(me)}</Text>
</View>
</>
);
}
Code of the Context.js connecting the react-native app to the signaling server:
import React, { createContext, useState, useRef, useEffect } from 'react';
import { io } from 'socket.io-client';
import Peer from 'simple-peer';
const SocketContext = createContext();
const socket = io('http://10.0.2.2:8082'); // use this to access via android emulator
//const socket = io('http://192.168.178.106:8082'); //use this to access via SmartTv Fire Tv Stick
const ContextProvider = ({ children }) => {
const [callAccepted, setCallAccepted] = useState(false);
const [callEnded, setCallEnded] = useState(false);
const [stream, setStream] = useState();
const [name, setName] = useState('');
const [call, setCall] = useState({});
const [me, setMe] = useState('');
const userVideo = useRef();
const connectionRef = useRef();
useEffect(() => {
socket.on('me', (id) => setMe(id));
socket.on('callUser', ({ from, name: callerName, signal }) => {
setCall({ isReceivingCall: true, from, name: callerName, signal });
});
}, []);
const answerCall = () => {
setCallAccepted(true);
const peer = new Peer({ initiator: false, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('answerCall', { signal: data, to: call.from });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
peer.signal(call.signal);
connectionRef.current = peer;
};
/* const callUser = (id) => {
const peer = new Peer({ initiator: true, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('callUser', { userToCall: id, signalData: data, from: me, name });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
socket.on('callAccepted', (signal) => {
setCallAccepted(true);
peer.signal(signal);
});
connectionRef.current = peer;
};*/
const leaveCall = () => {
setCallEnded(true);
connectionRef.current.destroy();
};
return (
<SocketContext.Provider value={{
call,
callAccepted,
setCallAccepted,
userVideo,
stream,
name,
setName,
callEnded,
me,
leaveCall,
answerCall,
}}
>
{children}
</SocketContext.Provider>
);
};
export { ContextProvider, SocketContext };
Code of the Context.js connecting the web react frontend to the signaling server:
import React, { createContext, useState, useRef, useEffect } from 'react';
import { io } from 'socket.io-client';
import Peer from 'simple-peer';
const SocketContext = createContext();
// const socket = io('http://localhost:5000');
const socket = io('http://localhost:8082');
const ContextProvider = ({ children }) => {
const [callAccepted, setCallAccepted] = useState(false);
const [callEnded, setCallEnded] = useState(false);
const [stream, setStream] = useState();
const [name, setName] = useState('');
const [call, setCall] = useState({});
const [me, setMe] = useState('');
const myVideo = useRef();
const userVideo = useRef();
const connectionRef = useRef();
useEffect(() => {
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((currentStream) => {
setStream(currentStream);
myVideo.current.srcObject = currentStream;
});
socket.on('me', (id) => setMe(id));
socket.on('callUser', ({ from, name: callerName, signal }) => {
setCall({ isReceivingCall: true, from, name: callerName, signal });
});
}, []);
const answerCall = () => {
setCallAccepted(true);
const peer = new Peer({ initiator: false, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('answerCall', { signal: data, to: call.from });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
peer.signal(call.signal);
connectionRef.current = peer;
};
const callUser = (id) => {
const peer = new Peer({ initiator: true, trickle: false, stream });
peer.on('signal', (data) => {
socket.emit('callUser', { userToCall: id, signalData: data, from: me, name });
});
peer.on('stream', (currentStream) => {
userVideo.current.srcObject = currentStream;
});
socket.on('callAccepted', (signal) => {
setCallAccepted(true);
peer.signal(signal);
});
connectionRef.current = peer;
};
const leaveCall = () => {
setCallEnded(true);
connectionRef.current.destroy();
window.location.reload();
};
return (
<SocketContext.Provider value={{
call,
callAccepted,
myVideo,
userVideo,
stream,
name,
setName,
callEnded,
me,
callUser,
leaveCall,
answerCall,
}}
>
{children}
</SocketContext.Provider>
);
};
export { ContextProvider, SocketContext };
In my opinion the error lies in the RTCView of the Callscreen but i have no idea how to fix it. Your help is very much appreciated!
Thank you very much!
[1]: https://i.stack.imgur.com/YBh9P.jpg
The library that you are using is probably using the SubtleCrypto.generateKey function to generate shared secrets. This API is "only available in a secure context", which means that it can only be used if the page is served over HTTPS.
Serve your page over HTTPS, and the error should go away.
I'm having a hard time trying to fix my login page
I've provided a very short youtube video on what is the problem that I encountered.
Youtube Link: https://youtu.be/lpyJo6tmiRs
It works properly on localhost but breaks when I deploy to herkou & netlify.
Register function also works properly
I provided everything here and also hidden some important info like mongodb user and passwords.
Website Link
https://incomparable-speculoos-abdd5f.netlify.app/
Login Page
import React, { useState, useEffect } from 'react'
import { useNavigate } from "react-router-dom"
import Axios from 'axios'
import './login.css'
import Register from '../register/register'
const Login = () => {
const navigate = useNavigate();
const [style, setStyle] = useState('hidden')
const [border, setBorder] = useState(false)
const [email, setEmail] = useState('')
const [password, setPass] = useState('')
const [errMsg, setErr] = useState('')
Axios.defaults.withCredentials = true;
const handleEmail = (e) => {
setEmail(e.target.value)
}
const handlePassword = (e) => {
setPass(e.target.value)
}
const show = () => [
setStyle('registerParent')
]
const hide = () => {
setStyle('hidden')
}
const reloadA = () => {
window.location.reload(false);
}
// FUNCTION WHEN LOGIN IS CLICKED
const login = () => {
Axios.post('https://votereact-app.herokuapp.com/login',
{email: email,
password: password,
}).then((response) => {
// CHECKS IF THERE IS A MESSAGE FROM THE BACKEND (MEANS THERE IS A PROBLEM IN THE LOGIN)
if (response.data.message) {
setErr(response.data.message)
setBorder(true)
} else {
// NAVIGATES TO /home ROUTE OF THERE IS NO MESSAGE (/route redirects to privateRoute)
setErr("Logged in")
setBorder(false)
navigate('/home', {replace: true})
}
})
}
return (
<>
<div className="loginParent">
<div className="loginContainer">
<h1 className="vote-login">VoteReact</h1>
<div className="loginBox">
<div className="inputs-parent">
<input type="text" style={{border: border ? '1px solid #e2252b' : '1px solid #1B74E4'}} placeholder="Email" className="email-input" onChange={handleEmail}></input>
<input type="password" style={{border: border ? '1px solid #e2252b' : '1px solid #1B74E4'}}placeholder="Password" className="password-input" onChange={handlePassword}></input>
<p className="errMsg">{errMsg}</p>
</div>
<button className="loginButton" onClick={login}>Log in</button> {/* LOGIN BUTTON */}
<p className="forgot">Forgot Password?</p>
<button className="signup" onClick={show}>Sign up</button>
</div>
</div>
</div>
<Register styleName={style.toString()} close={() => hide()} load={() =>reloadA()}/>
</>
)
}
export default Login
BACK END CODE
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose")
const app = express();
const bcrypt = require("bcryptjs")
const saltRounds = 10;
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser")
const session = require("express-session")
const voterModel = require('./modules/voters.js')
const presidentModel = require('./modules/president.js')
const viceModel = require('./modules/vice.js')
const treasurerModel = require('./modules/treasurer.js')
app.use(express.json());
require('dotenv').config();
app.use(cors({credentials: true, origin: 'https://incomparable-speculoos-abdd5f.netlify.app'}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(session({
key: "userId",
secret: "hidden",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 60000
}
}))
mongoose.connect("hidden",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
// GET THE SESSION AND CHECK IF IT DOES EXIST OR NO
//IF YES THEN LOGGEDIN: TRUE ELSE, FALSE
// --- HERE IS WHERE I ENCOUNTER PROBLEM, IT SHOULD RETURN TRUE AFTER I LOG IN BUT STILL RETURNS FALSE ---
app.get('/login', async (req, res) => {
if (req.session.voter) {
res.send({loggedIn: true})
} else {
res.send({loggedIn: false})
}
})
app.post('/login', async (req, res) => {
const email = req.body.email;
const password = req.body.password;
// CHECKS IF USER EMAIL EXISTS
voterModel.find({email: email}, {"email":1}, async (err, result) => {
if (err) {
console.log(err)
} else {
if(result.length > 0) {
// COMPARES PASSWORD IF IT IS CORRECT
const user = await voterModel.findOne({email: email})
const pass = await user.comparePassword(password)
if (pass) {
// SAVE THE SESSION IF PASS IS CORRECT
req.session.voter = result
var oneWeek = 60 * 60 * 24; //1 week
req.session.voter.expires = new Date(Date.now() + oneWeek);
req.session.voter.maxAge = oneWeek;
console.log(req.session.voter)
res.send(result)
} else {
console.log("NOT LOGGED IN")
res.send({ message: 'Invalid email or password!'})
}
} else {
console.log("NOT LOGGED IN")
res.send({ message: 'Invalid email or password!'})
}
}
})
})
app.post('/register', async (req, res) => {
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
// HASING PASSWORD
bcrypt.hash(password, saltRounds, async (err, hash) => {
if (err) {
console.log(err)
}
// INSERTING VALUES
const voters = await voterModel({email: email, username: username, password: hash, status: false})
// CHECKS IF EMAIL IS IN USE
const isNewEmail = await voterModel.isThisEmailInUse(email)
if (!isNewEmail) return res.send({ message: 'This email is already taken!'})
// SAVES THE INSERT DATA FOR VOTERS
await voters.save()
res.send({success: true})
})
})
app.post('/logout', (req, res) => {
if(req.session.voter) {
req.session.voter = null;
req.session.destroy();
}
})
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log('Running on port successfuly')
})
Private Route to Home
import React, { useState, useEffect } from 'react'
import { useNavigate } from "react-router-dom"
import Axios from 'axios'
import Home from "./home/home.js"
const PrivateRoute = () => {
Axios.defaults.withCredentials = true;
const navigate = useNavigate();
const [loggedIn, setLoggedIn] = useState(false);
useEffect(()=> {
// GET DATA FROM axios.get(/login) on backend
Axios.get("https://votereact-app.herokuapp.com/login").then((response) => {
if (response.data.loggedIn === true) {
setLoggedIn(true);
console.log(response)
} else {
navigate("/" , {replace: true})
console.log(response)
}
})
},[])
// WHILE CHECKING IF Logged in or not
if (!loggedIn) {
return (
<>
Loading...
</>
)
}
// Redirects to real home page if user is logged in
return (
<>
<Home/>
</>
)
}
export default PrivateRoute
I am using react native for frontend and django for backend of my application, but I can't make an api request with axios to login authentication.
I would like to know why the request is not made to the backend but is rejected.
The code fails during the request, up to which point it is executed.
userSlice:
import axios from "axios";
import { createAsyncThunk, createSlice } from "#reduxjs/toolkit";
const initialState = {
isLoading:false,
isSuccess:false,
isError:false,
message:"",
userInfo: null
}
export const login = createAsyncThunk(
'user/login',
async (userData, thunkApi) => {
try{
const config = {
headers:{
'Content-type':'application/json'
}
}
const response = await axios.post(
'http://127.0.0.1:8000/api/users/login/',
userData,
config
)
return response.data
}catch(error){
return thunkApi.rejectWithValue(error.response?.data)
}
})
const userSlice = createSlice({
name:"user",
initialState,
reducers:{
},
extraReducers: (builder) => {
builder.addCase(login.pending, (state) => {
state.isLoading = true
})
builder.addCase(login.fulfilled, (state, action) => {
state.isLoading = false
state.isSuccess = true
state.userInfo = action.payload
})
builder.addCase(login.rejected, (state, action) => {
state.isLoading = false
state.isSuccess = true
state.userInfo = null
state.message = action.payload
})
}
})
export default userSlice.reducer
store:
import {configureStore, combineReducers} from '#reduxjs/toolkit'
import userReducer from './userSlice'
const rootReducer = combineReducers({
user: userReducer
})
export const store = configureStore({
reducer: rootReducer
})
export default store
login dispatch:
const onPressHandler = () =>{
dispatch(login({username, password}))
}