Facing error while requesting the signup request - axios

who I'm and what I'm trying to do :
I am a beginner following and building a MERN stack project tutorial on youtube
I want to make two requests to the server :
the first request is a register/ signUp request (not working fine).
the second request is a login request (working fine).
errors in my console
POST http://localhost:5000/auth/register 500 (Internal Server Error)
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
my console looks like this
source code:
Auth.jsx
const handleSubmit = (e) => {
// setConfirmPass(true);
e.preventDefault();
if (isSignUp) {
data.password === data.confirmpass
? dispatch(signUp(data))
: setConfirmPass(false);
} else {
dispatch(logIn(data));
}
};
AuthRequest.js
import axios from "axios";
const API = axios.create({ baseURL: "http://localhost:5000" });
export const logIn = (formdata) => API.post("/auth/login", formdata);
export const signUp = (formdata) => API.post("/auth/register", formdata);
AuthAction.js
import * as AuthAPI from "../api/AuthRequest.js";
export const logIn = (formData) => async (dispatch) => {
dispatch({ type: "AUTH_START" });
try {
const { data } = await AuthAPI.logIn(formData);
dispatch({ type: "AUTH_SUCCESS", data: data });
} catch (error) {
console.log(error);
dispatch({ type: "AUTH_FAIL" });
}
};
export const signUp = (formData) => async (dispatch) => {
dispatch({ type: "AUTH_START" });
try {
const { data } = await AuthAPI.signUp(formData);
dispatch({ type: "AUTH_SUCCESS", data: data });
} catch (error) {
console.log(error);
dispatch({ type: "AUTH_FAIL" });
}
};
Can somebody tell me why my sighUp request is showing me an error and login is working fine. How to fix that errors.
both request are working fine using thunderclient.
Sorry If I am not able to understand properly here what my problem is. you can open the youtube video link (at time 45:44). this is what I'm trying to do. I have added the cors package also but for the sighup request it is not working.

Related

Axios stream ECONNRESET But which side error'd

I am using axios to stream data from an API, something like this
const response = await axios.get(url,
{
responseType: `stream`,
}
);
const stream = response.data;
stream.on(`data`, (data) => {
...
});
stream.on(`error`, (err) => {
...
});
From time-to-time I get an error
{
"code": "ECONNRESET"
}
Does this mean it's the API that is throwing this error as opposed to my application that caused it?
Thank you,

Axios interceptor not working anymore in last version (1.1.3)

I recently upgraded axios in one of my project (from 0.27 to 1.1.3) and the interceptor I created to refresh the user's access token doesn't work anymore, u can find in the screenshot bellow the error I'm having. I searched online but can't find anything working.
To precise, whenever the user's access token expires, my back end send the 401 error and so the interceptor is called. The returned token is good as well as the setting to the headers.
Thank you in advance for your time.
import axios from "axios";
import router from "#/router";
import store from "#/store/index";
const instance = axios.create({
baseURL: "http://localhost:3000",
});
instance.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
console.log("error:", error);
if (
error.config.url != "users/refreshToken" &&
error.response.status === 401 &&
!originalRequest._retry
) {
originalRequest._retry = true;
await instance
.get("users/refreshToken", { withCredentials: true })
.then((response) => {
const token = response.data.accessToken;
console.log("token:", token);
store.state.token = token;
instance.defaults.headers.common["authorization"] = `Bearer ${token}`;
originalRequest.headers["authorization"] = `Bearer ${token}`;
localStorage.setItem("token", token);
})
.catch(() => {
store.commit("logout");
localStorage.removeItem("token");
router.push({ name: "login", params: { error: "refreshToken" } });
});
return instance(originalRequest);
}
return Promise.reject(error);
}
);
export default instance;
The error :

Axios `PUT` 500 Error when trying to add contract to sendgrid

I am trying to take user emails and put them into sendgrid as a contract list. It seems like some information is being lost when trying to add new emails to the list but am unsure exactly what is causing the problem.
First I have a hero component that contains the area of email collection:
const Hero = () => {
const [mail, setMail] = useState(null);
const [loading, setLoading] = useState(false);
//Called onClick()
const subscribe = () => {
setLoading(true);
axios.put("api/sendgrid/mailingList", mail)
.then((result) => {
if (result.status === 200) {
toast.success(result.response.data);
setLoading(false);
}
})
.catch((error) => {
console.log(error.response.data);
setLoading(false);
});
};
The axios put from the previous section goes to my api/sendgrid/mailingList:
import axios from "axios";
export default async function handler(req, res) {
if (req.method === "PUT") {
await axios.put("https://api.sendgrid.com/v3/marketing/contacts", {
contacts: [{ email: req.body.mail }],
list_ids: [process.env.SENDGRID_MAILING_ID],
},
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.NEXT_PUBLIC_SENDGRID}`,
},
}
)
.then((res) => {
res.status(200).send({
message:
"Your email has been succesfully added to the mailing list. Welcome 👋",
});
})
.catch((error) => {
res.status(500).send({
message:
"There was a problem with your subscription, please try again or contact us",
});
});
}
}
I am able to access my API script but am met with the following error:
PUT http://localhost:3000/api/sendgrid/mailingList 500 (Internal
Server Error)
The network tab on the console tools:

Fail to save user to mongodb

If I remain this code, the program still working, my image will upload backend to frontend normally
router.post('/admin/register', upload.single('avatar'), async (req, res) => {
// Handle add image by multer
... handel file upload from front-end
return res.json({ avatar: newFullPath });
}
);
I started save user to mongoDB and error occur
router.post('/admin/register', upload.single('avatar'), async (req, res) => {
// Handle add image by multer
... handel file upload from front-end
//Handle add user to database
const user = {
...JSON.parse(req.body.user),
avatar: newFullPath
}; // { first_name: 'John', last_name: 'Wick', avatar: .... }
const { error } = Validation.adminRegisterValidation(user);
if (error) {
return res.json({ error: error.details[0].message });
} // working as I expected
const emailExist = await User.findOne({ email: user.email });
if (emailExist) {
return res.json({ error: 'Email already exist!' });
} // working as I expected
// If I commented this block of code, program still run as I expected, but if I don't do
// that, the program crashed ( Error: Below images )
const hashedPassword = bcrypt.hashSync(user.password, 10);
const addUser = new User({
first_name: user.first_name,
last_name: user.last_name,
avatar: user.avatar
});
await addUser.save();
return res.json({ avatar: newFullPath });
}
);
This project in my Github repository: This project in Github
Error shows in console
Error in Network

How to Use Rest api with React Native; Network Call Issues

I am newbie in React Native,
I made a simple back-end using Mongodb and express routes etc in MongoDb atlas. I am successfully able to post/get/patch/Delete operation on mongodb atlas that store Title and Description using Postman. Everything is working fine.
Here comes the problem First when i make a simple frontend in ReactNative that take inputs Title and Description. I want application that take simple input of Title and Description and on Submit Button it store into the the mongodb Atlas just like postman is doing. I tried but its not working code is below. I dont know how to communicate the front end into backend. I watch alot of tutorials but unable to get the point.
Secondly, when i make a server i wrote in pakage.json > "start": "nodemone server.js" and i need to run ReactNative app i update the pakage.json > "start": "expo start" to run app. How can i run server and expo app same time? if i seprate the app folder then how can i connect both of them.
below is my Code.
Routes folder post.js
const express = require( 'express' );
const router = express.Router();
const Post = require ('../models/Post')
//Gets back all the posts
router.get ( '/', async (req, res) =>{
try{
const post = await Post.find();
res.json(post);
}catch (err) {
res.json({message: err })
}
});
//To Submit the Post
router.post('/', async (req, res) =>{
//console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description
});
try{
const savedPost = await post.save();
res.json(savedPost);
}catch (err) {
res.json ({ message: err })
}
});
//Get back specific Post
router.get('/:postId', async (req, res) =>{
try{
const post= await Post.findById(req.params.postId);
res.json(post);
}catch(err) {
res.json({message: err });
}
})
// to delete specific post
router.delete('/:postId', async (req, res) =>{
try{
const removePost= await Post.remove({_id: req.params.postId});
res.json(removePost);
}catch(err) {
res.json({message: err });
}
})
//update Post
router.patch('/:postId', async (req, res) =>{
try{
const updatePost = await Post.updateOne(
{_id: req.params.postId},
{ $set:
{title: req.body.title}
});
res.json(updatePost);
}catch(err) {
res.json({message: err });
}
})
module.exports = router;
Defined Schema Post.js
const mongoos = require( 'mongoose' );
const PostSchema = mongoos.Schema ({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = mongoos.model ('Post', PostSchema); // giving this schma name Post
server.js
const express = require( 'express' );
const app = express();
var mongo = require('mongodb');
const mongoos = require( 'mongoose' );
const bodyParser = require('body-parser');
require('dotenv/config');
const postRoute = require('./Routes/post');
app.use(bodyParser.json());
app.use ('/post', postRoute);
app.get ( '/', (req, res) =>{
res.send('We are on Home ')
});
// connecting to database
mongoos.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log('Connected to db')
);
app.listen(3000);
Frontend Form.js
import React from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
class Form extends React.Component{
constructor(){
super();
this.State = {
title: '',
description: ''
}
}
getInput(text, field){
if(field == 'title')
{
this.setState({ title: text, })
}
else if(field == 'description')
{
this.setState({ description: text, })
}
//console.warn(text)
}
submit(){
let collection={}
collection.title = this.state.title,
collection.description = this.state.description;
console.warn(collection);
var url = process.env.DB_CONNECTION ;
fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
collection
}),
});
}
render() {
return (
<View style={styles.container}>
<TextInput style={styles.inputBox}
underlineColorAndroid= 'rgba(0,0,0,0)'
placeholder='Title'
selectionColor="#fff"
keyboardType="default"
onChangeText = {(text) => this.getInput(text, 'title')}
/>
<TextInput style={styles.inputBox}
multiline = {true}
numberOfLines = {4}
underlineColorAndroid= 'rgba(0,0,0,0)'
placeholder='Description'
selectionColor="#fff"
keyboardType="default"
onChangeText= {(text) => this.getInput(text, 'description')}
/>
<TouchableOpacity onPress={()=>this.submit()} style={styles.btn} >
<Text style={{textAlign: 'center'}}>Submit</Text>
</TouchableOpacity>
</View>
);
}
}
export default Form;
Here comes a very basic solution to your problem:
1: if you are using Rest API based model of communication go for Two separate repos on GITHUB. One for React native app of yours and one for server-side of yours.
2: now to go to Heroku.com and make an app there and attach your card there in order to use the full Free Sandbox functionality
3: create a project there and find an option to deploy from Github.
4: for data communication aka network requests its easy to use axios rather than Fetch
for best practices use :
https://riptutorial.com/react-native/topic/857/getting-started-with-react-native
5: in order to run more than one command in package json able to run multiple scripts in package.json you can either do it like
scripts:{"run": "yarn start" && "react-native-expo"}
6: or if your scripts are like they gonna need to run constantly in the background it's better that you create two separate scripts
scripts:{"run1": "yarn start", "run2":"yarn start2"}
7: I see you are not handling the AsyncAwait Try catch or Promise after the fetch
8: you are also not hitting the server-side URL seemingly you are hitting DB connection url. what you should be doing is that you hit the POST/GET/UPDATE routing endpoint of yours