Cannot read property 'create' of undefined error when integrating Shippo - node.js

I am working on a product using node.js in my backend and react.js in my frontend. In this project, I am trying to integrate Shippo. They provide api information for the backend, which I have tried to use/follow. I am currently getting a cannot read property 'create' of undefined error, which is a POST 500 Internal Server Error from the backend, but I an unsure why I am getting this error and if I am integrating this system correctly. I would really appreciate any help or advice on what I could be doing wrong. Thank you!
Backend:
Shippo.js
'use strict';
import express from 'express';
import shippo from 'shippo';
const shippoToken = process.env.SHIPPO_TOKEN || ''
const shippoRouter = express.Router();
shippoRouter.post(
'/shippinginfo',
function (req, res) {
var addressFrom = {
"name": "Jane Smith",
"street1": "500 Riveride Dr",
"city": "New York",
"state": "NY",
"zip": "10002",
"country": "US"
};
const to = req.body
var addressTo = shippo.address.create({
"name": to.fullName,
"street1": to.address1,
"street2": to.address2,
"city": to.city,
"state": to.state,
"zip": to.postalCode,
"country": to.country,
"phone": to.phoneNumber,
"email":to.email,
"validate": true,
}, function(err, address) {
// asynchronously called
});
// asynchronously called
console.log(addressFrom)
console.log(addressTo)
var parcel = {
"length": "5",
"width": "5",
"height": "5",
"distance_unit": "in",
"weight": "2",
"mass_unit": "lb"
};
/*
shippo.shipment.create({
"address_from": addressFrom,
"address_to": addressTo,
"parcels": [parcel],
"async": false
}, function(err, shipment){
// asynchronously called
});
shippo.shipment.rates('5e40ead7cffe4cc1ad45108696162e42');
//var rate = shipment.rates[0];
// Purchase the desired rate.
shippo.transaction.create({
"rate": rate.object_id,
"label_file_type": "PDF_4x6",
"async": false
}, function(err, transaction) {
// asynchronous callback
});*/
});
export default shippoRouter;
server.js
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import path from 'path';
import shippoRouter from './shippo.js';
dotenv.config();
const app = express();
app.use(cors()); //and this
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/AM', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
app.use('/api/shippo', shippoRouter);
app.get('/', (req, res) => {
res.send('Server is ready');
});
app.use((err, req, res, next) => {
res.status(500).send({ message: err.message });
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serve at http://localhost:${port}`);
});
How I tried to get the shipping information from my frontend using axios
Frontend:
ShippingAddressScreen.js
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { saveShippingAddress } from '../actions/cartActions';
import CheckoutSteps from '../components/CheckoutSteps';
import { shippingInfo } from '../actions/shippingActions';
export default function ShippingAddressScreen(props) {
const userSignin = useSelector((state) => state.userSignin);
const { userInfo } = userSignin;
const cart = useSelector((state) => state.cart);
const { shippingAddress } = cart;
if (!userInfo) {
props.history.push('/signin');
}
const [fullName, setFullName] = useState(shippingAddress.fullName);
const [address1, setAddress1] = useState(shippingAddress.address1);
const [address2, setAddress2] = useState(shippingAddress.address2);
const [city, setCity] = useState(shippingAddress.city);
const [state, setState] = useState(shippingAddress.state);
const [postalCode, setPostalCode] = useState(shippingAddress.postalCode);
const [country, setCountry] = useState(shippingAddress.country);
const [phoneNumber, setPhoneNumber] = useState('');
const [email, setEmail] = useState('');
const name = fullName;
const street1 = address1;
const street2 = address2;
const zip = postalCode;
const phone = phoneNumber;
const dispatch = useDispatch();
const submitHandler = (e) => {
e.preventDefault();
dispatch(
saveShippingAddress({ fullName, address1, address2, city, state, postalCode, country })
);
props.history.push('/payment');
dispatch(
shippingInfo({ name, street1, street2, city, state, zip, country, phone, email })
);
};
/* const shippingInfo = (e) => {
e.preventDefault();
};*/
return (
<div>
<CheckoutSteps step1 step2></CheckoutSteps>
<form className="form" onSubmit={submitHandler}>
<div>
<h1>Shipping Address</h1>
</div>
<div>
<label htmlFor="fullName">Full Name</label>
<input
type="text"
id="fullName"
placeholder="Enter full name"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="address1">Address</label>
<input
type="text"
id="address1"
placeholder="Enter address"
value={address1}
onChange={(e) => setAddress1(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="address2">Address</label>
<input
type="text"
id="address2"
placeholder="Enter address"
value={address2}
onChange={(e) => setAddress2(e.target.value)}
></input>
</div>
<div>
<label htmlFor="city">City</label>
<input
type="text"
id="city"
name="city"
placeholder="Enter city"
value={city}
onChange={(e) => setCity(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="state">State</label>
<input
type="text"
id="state"
placeholder="Enter state"
value={state}
onChange={(e) => setState(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="postalCode">Postal Code</label>
<input
type="text"
id="postalCode"
placeholder="Enter postal code"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="country">Country</label>
<input
type="text"
id="country"
placeholder="Enter country"
value={country}
onChange={(e) => setCountry(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="phoneNumber">Phone Number</label>
<input
type="text"
id="phoneNumber"
placeholder="Enter Phone Number"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
required
></input>
</div>
<div>
<label htmlFor="email">Email</label>
<input
type="text"
id="email"
placeholder="Enter Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
></input>
</div>
<div>
<button className="primary" type="submit">
Continue
</button>
</div>
</form>
</div>
);
}
ShippingActions.js
import Axios from 'axios';
import {
SHIPPING_ADDRESS_FAIL,
SHIPPING_ADDRESS_REQUEST,
SHIPPING_ADDRESS_SUCCESS,
} from '../constants/shippingConstants';
export const shippingInfo = (name, street1, street2, city, state, zip, country, phone, email) => async (dispatch) => {
dispatch({ type: SHIPPING_ADDRESS_REQUEST, payload: { name, email} });
try {
const { data } = await Axios.post('/api/shippo/shippinginfo', {
name,
street1,
street2,
city,
state,
zip,
country,
phone,
email,
});
dispatch({ type: SHIPPING_ADDRESS_SUCCESS, payload: data });
} catch (error) {
dispatch({
type: SHIPPING_ADDRESS_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
I also have a shippingReducer, shippingConstants, and included the reducer in my store.js.
Also, if this is helpful https://goshippo.com/docs/reference/js#overview is Shippo's Api Information.

I am currently getting a cannot read property 'create' of undefined error
From the code you shared, it looks like you are not initializing the shippo module correctly in Shippo.js, therefore shippo.create method does not exist.
In your code, you are importing the shippo module, but not initializing it with the key:
import shippo from 'shippo';
const shippoToken = process.env.SHIPPO_TOKEN || ''
// <omitted>
var addressTo = shippo.address.create({
// <omitted>
Note that shippoToken remains unused in your file.
In the Shippo library documentation, they have the following example:
var shippo = require('shippo')('<YOUR_PRIVATE_KEY>');
Since you are using ES modules, you can't use this one-liner, so try something like this instead:
import shippo from 'shippo';
const shippoToken = process.env.SHIPPO_TOKEN || ''
// initialize the shippo constructor with token:
const shippoClient = shippo(shippoToken);
// now you can use shippoClient instead of shippo:
var addressTo = shippoClient.address.create({
// <omitted>

Related

Unable to signup once login detail have been entered

I'm pretty new to React & node.js , and have attempted to create a chat messaging app. However im unable to access the rest of my app as every-time i sign in there is an error stating:
**Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16:1)
at settle (settle.js:17:1)
at XMLHttpRequest.onloadend (xhr.js:66:1)**
Auth.jsx file in client server
import React, {useState} from 'react';
import Cookies from 'universal-cookie';
import axios from 'axios';
import signinImage from '../assets/Group 2.png';
const cookies = new Cookies();
//forming the inital state of input fields
const initialState = {
fullName:'',
username:'',
password:'',
confirmPassword:'',
phoneNumber:'',
avatarURL:'',
}
const Auth = () => {
const [form, setForm] = useState(initialState);
const [isSignup , setIsSignup] = useState(true);
const handleChange = (e) => {
setForm({...form,[e.target.name]: e.target.value});
}
const handleSubmit = async (e)=>{
e.preventDefault();
const {username , password , phoneNumber , avatarURL } = form;
const URL = 'http://localhost:5009/auth'
//making requests to different url backened each time
const {data : { token ,userId , hashedPassword , fullName }} = await axios.post(`${URL}/${isSignup ? 'Sign Up ' : 'Sign In'}`,{
username , password , fullName: form.fullName , phoneNumber , avatarURL,
})
//storing data in cookies
cookies.set('token ' , token )
cookies.set('username ' , username )
cookies.set('fullName' , fullName)
cookies.set('userId ' , userId )
if (isSignup){
cookies.set('phoneNumber' , phoneNumber )
cookies.set('avatarURL' , avatarURL)
cookies.set('hashedPassword' , hashedPassword )
}
//reloads application
window.location.reload();
}
//changing state of my sign up screen depending on the state before
const switchMode = () => {
setIsSignup((prevIsSignup) => !prevIsSignup);
}
return (
<div className=" auth__form-container">
<div className="auth__form-container_fields">
<div className="auth__form-container_fields-content">
<p>{isSignup ? 'Sign up' : 'Sign In'}</p>
<form onSubmit= {handleSubmit}>
{isSignup &&(
<div className= "auth__form-container_fields-content_input">
<label htmlFor="fullName">Full Name</label>
<input
name="fullName"
type="text"
placeHolder= "Full Name"
onChange={handleChange}
required
/>
</div>
) }
<div className= "auth__form-container_fields-content_input">
<label htmlFor="username">Username</label>
<input
name="username"
type="text"
placeHolder= "Username"
onChange={handleChange}
required
/>
</div>
{isSignup &&(
<div className= "auth__form-container_fields-content_input">
<label htmlFor="phoneNumber">Phone Number</label>
<input
name="phoneNumber"
type="text"
placeHolder= "Phone Number"
onChange={handleChange}
required
/>
</div>
) }
{isSignup &&(
<div className= "auth__form-container_fields-content_input">
<label htmlFor="avatarURL">Avatar URL</label>
<input
name="avatarURL"
type="text"
placeHolder= "Avatar URL"
onChange={handleChange}
required
/>
</div>
) }
<div className= "auth__form-container_fields-content_input">
<label htmlFor="password">Password</label>
<input
name="password"
type="password"
placeHolder= "Password"
onChange={handleChange}
required
/>
</div>
{isSignup &&(
<div className= "auth__form-container_fields-content_input">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
name="confirmPassword"
type="password"
placeHolder= "Confirm Password"
onChange={handleChange}
required
/>
</div>
) }
<div className="auth__form-container_fields-content_button">
<button>{isSignup ? "Sign up " : "Sign In"}</button>
</div>
</form>
<div className="auth__form-container_fields-account">
<p>
{isSignup
? "Already have an account?"
:"Dont have an account ?"
}
<span onClick={switchMode}>
{isSignup ? ' Sign In' : ' Sign up'}
</span>
</p>
</div>
</div>
</div>
<div className="auth__form-container_image">
<img src = {signinImage} alt ="Sign In" />
</div>
</div>
)
}
export default Auth
Below is the code for files in my server folder :
index.js
const express = require ('express');
const cors = require ('cors');
//adding routes for sign in + registrationn//
const authRoutes = require("./routes/auth.js");
const app = express ();
const PORT = process.env.PORT || 5009;
require ('dotenv').config();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded());
app.get('/' , (req,res) => {
res.send('ne, world');
});
app.use('/auth', authRoutes);
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Auth.js file in Controllers folder:
const { connect } = require('getstream');
const bcrypt = require('bcrypt');
const StreamChat = require('stream-chat').StreamChat;
const crypto = require('crypto');
require('dotenv').config();
const api_key = process.env.STREAM_API_KEY;
const api_secret = process.env.STREAM_API_SECRET;
const app_id = process.env.STREAM_APP_ID;
const signup = async (req, res) => {
try {
const { fullName, username, password, phoneNumber } = req.body;
const userId = crypto.randomBytes(16).toString('hex');
const serverClient = connect(api_key, api_secret, app_id);
const hashedPassword = await bcrypt.hash(password, 10);
const token = serverClient.createUserToken(userId);
res.status(200).json({ token, fullName, username, userId, hashedPassword, phoneNumber });
} catch (error) {
console.log(error);
res.status(500).json({ message: error });
}
};
const login = async (req, res) => {
try {
const { username, password } = req.body;
const serverClient = connect(api_key, api_secret, app_id);
const client = StreamChat.getInstance(api_key, api_secret);
const { users } = await client.queryUsers({ name: username });
if(!users.length) return res.status(400).json({ message: 'User not found' });
const success = await bcrypt.compare(password, users[0].hashedPassword);
const token = serverClient.createUserToken(users[0].id);
if(success) {
res.status(200).json({ token, fullName: users[0].fullName, username, userId: users[0].id});
} else {
res.status(500).json({ message: 'Incorrect password' });
}
} catch (error) {ads
console.log(error);
res.status(500).json({ message: error });
}
};
module.exports = { signup, login }
Auth.js file in routes folder
const express = require ('express');
const { signup, login } = require('../controllers/auth.js');
const router = express.Router();
//initialising my 2 different routes //
//post route sending data from frontend to backend
router.post('/signup', signup);
router.post('/login', login);
module.exports = router;
Any thought on what im doing wrong or can implement to change these errors would be much appreciated !

Failed to send image along with other data from react to node backend

I am trying to send form data along with image from react frontend to node backend though I am getting other data but image filed is empty.Below is my code:
form.js
import React, { useState } from 'react'
const Form = () => {
const [title, setTitle] = useState("");
const [author, setAuthor] = useState("");
const [chapter, setChapter] = useState("");
const [price, setPrice] = useState("");
const [file, setFile] = useState("");
const submitData = async (e) => {
e.preventDefault();
if (file === '') {
alert('Choose file');
}
else {
const data = {
title: title,
auth: author,
chap: chapter,
cost: price,
filename: file
}
console.log(data); //Here file object showing in console
const res = await fetch('http://localhost:2000/api/addBook', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ myData:data})
});
const res2 = await res.json();
console.log(res2);
}
}
const saveFile = (e) => {
setFile(e.target.files[0]);
};
return (
<div className='container'>
{/* <div className="contact">
<h1>Add book</h1>
</div> */}
<div className="form card">
<h1>Add book</h1>
<input type="text" className='form-control' id="title" name="title" placeholder="Title" onChange={e => setTitle(e.target.value)} />
<input type="text" className='form-control' id="author" name="author" placeholder="Author" onChange={e => setAuthor(e.target.value)} />
<input type="text" className='form-control' id="chapter" name="author" placeholder="Chapters (Separated by comma)" onChange={e => setChapter(e.target.value)} />
<input type="text" className='form-control' id="price" name="author" placeholder="Price" onChange={e => setPrice(e.target.value)} />
<input type="file" className='form-control' name="myImage" onChange={saveFile} />
<button className='btn btn-primary' type="submit" id="addData" onClick={submitData}>ADD</button>
</div>
</div>
react)
}
export default Form;
backend
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
app.use(fileUpload());
const addBook = async (req, res) => {
const { myData } = req.body;
// const file = req.files.profileImg; //Its showing error when I am using profileImg not found
console.log(myData);
}
module.exports = { addBook };
In backend terminal I am getting below output where filename object is empty:
{
title: 'nancy drew',
auth: 'unknown',
chap: 'First',
cost: '200',
filename: {}
}
How can I get file on backend side someone let me know.

What did I do wrong when I push database registers to Json-server to users.json. I have 404 not found

I am new to ReactJs coding, I have watched some videos about fake JSON-Server, but I don't know how to post all data from register.js to my "users.json" through "server.js".
What I do is I have an edit "package.json" "script": "auth": "node server.js" and npm i json-server, npm i json-server jsonwebtoken body-parser --save-dew and npm run auth to run server.js
I learn this on youtube...
Here is my source code. Someone can fix my wrong "post", Thank you!
users.json
{
"users": [
{
"id": 1
"username":"admin",
"email": "123#gmail.com",
"phone": "01234",
"pass": "admin1234",
"gender":"female",
"role":"shop"
}
]
}
server.js
const fs = require("fs");
const bodyParser = require("body-parser");
const jsonServer = require("json-server");
const jwt = require("jsonwebtoken");
const server = jsonServer.create();
const userdb = JSON.parse(fs.readFileSync("./database/users.json", "utf-8"));
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
server.use(jsonServer.defaults());
const SECRET_KEY = "85423112"; //*random key to see access-token
const expiresIn = "1h";
function createToken(payload) {
return jwt.sign(payload, SECRET_KEY, {expiresIn});
}
function isLoginAuthenticated({username, password}) {
return (
userdb.users.findIndex((user) => user.username === username && user.pass === password) !== -1
); ư
}
function isSignupAuthenticated({username}) {
return (
userdb.users.findIndex((user) => user.username === username ) !== -1);}
server.post("api/auth/register", (req,res)=>{
const {username,email,phone,password, gender,role} = req.body;
if(isSignupAuthenticated({username})){
const status = 401;
const message = "Username already taken";
res.status(status).json({status,message}) //*taken err will appeare in web console
return;
}
fs.readFile(".database/users.json", (err, data) => {
if(err){
const status = 401;
const message = "err";
res.status(status).json({status,message}) //*err when read file in system will appeare in web console
return;
}
data = JSON.parser(data.toString());
let last_item_id = data.users[data.user.length - 1].id;
data.users.push({id: last_item_id +1, username:username,email:email,phone: phone, pass:password, gender:gender, role:role });
let writeData = fs.writeFile("./database/users.json", JSON.stringify(data), (err, result)=>{
if (err) {
const status = 401;
const message = "err";
res.status(status).json({status,message})
return;
}
});
});
const access_token = createToken({username,password});
res.status(200).json({access_token}); //* set status to be OKKKKK when create account success =)))
});
server.post("/api/auth/login", (req,res)=>{
const {username,password} = req.body;
if(!isLoginAuthenticated({username,password})){
const status = 401;
const message = "Incorrect Username or Password";
res.status(status).json({status,message}) //*wrong will appeare in web console
return;
}
const access_token = createToken({username,password});
res.status(200).json({access_token}); //* set status to be OKKK when login ok =)))
});
server.listen(5001, ()=>{
console.log("running json api server");
});
Register.js
import React, {useState} from 'react'
import '../styles/Signup.css'
import axiox from "axios";
import {useHistory, Link} from 'react-router-dom'
import VisibilityIcon from '#mui/icons-material/Visibility'
import VisibilityOffIcon from '#mui/icons-material/VisibilityOff'
function Register() {
const [username,setUsername]= useState("");
const [password,setPassword]= useState("");
const [email,setEmail]= useState("");
const [phone,setPhone]= useState("");
const [gender,setGender]= useState("");
const [role,setRole]= useState("");
const [error, setError]= useState("");
let history = useHistory();
const [showPass,setshowPass]= useState(false);
const [showconfirmPass,setshowconfirmPass]= useState(false);
const register = (e) => {
e.preventDefault();
axiox.post("http://localhost:5001/api/auth/register",
{username,
email,
phone,
password,
gender,
role,
}).then((response)=> {
console.log("response", response)
localStorage.setItem("login", JSON.stringify({
userLogin: true,
token: response.data.access_token,
}));
setError("");
setUsername("");
setEmail("");
setPhone("");
setPassword("");
setGender();
setRole();
history.push("/login");
}).catch(error =>setError(error.response.data.message));
};
return (
<div>
<div id="getstarted">Get started</div>
<div id="intro"><span>Sign up</span> to our website and start to explore your unique style today !</div>
<div class="center">
<form onSubmit={register}>
<div class="txt_field">
<input type="text" required
value={username}
onChange={(e)=> setUsername(e.target.value)}/>
<span></span>
<label>Username</label>
</div>
<div class="txt_field">
<input type="text" required
value={email}
onChange={(e)=> setEmail(e.target.value)}/>
<span></span>
<label>Email</label>
</div>
<div class="txt_field">
<input type="text" required
value={phone}
onChange={(e)=> setPhone(e.target.value)}/>
<span></span>
<label>Phone number</label>
</div>
<div class="txt_field">
<input type={showPass ?"text":"password" }required
value={password}
onChange={(e)=> setPassword(e.target.value)}/>
<span></span>
<label>Password</label>
</div>
<div class="password1" onClick={()=>{if(showPass == true){setshowPass(false)}else {setshowPass(true)}}}>
{showPass ? <VisibilityIcon/> : <VisibilityOffIcon/>}
</div>
<div class="txtfield_1">
<input type={showconfirmPass ?"text":"password" } required/>
<span></span>
<label>Confirm Password</label>
</div>
<div class="confirm" onClick={()=>{if(showconfirmPass == true){setshowconfirmPass(false)}else {setshowconfirmPass(true)}}}>
{showconfirmPass ? <VisibilityIcon/> : <VisibilityOffIcon/>}
{error && <p2 style={{
color:"red",
position:"absolute",
top:"580px", width:"500px", left:"15vw"
}}>{error}</p2>}
</div>
<div id="general">
<div class="signup_link">
Already have an account? <Link to="/login">Sign in</Link>
</div>
<input type="submit" value="Learn More"/>
</div>
</form>
</div>
<div id="rightside">
<div id="sex">Sex</div>
<div id="button">
<input type="radio" name="gender" value={gender =="male"} onChange={(e)=> setGender(e.target.value)}/>
<label for="male"></label>
<span>Male</span>
<input type="radio" name="gender" value={gender =="female"} onChange={(e)=> setGender(e.target.value)}/>
<label for="female"></label>
<span>Female</span>
</div>
<div class="rect1">
<button class="button" type="button" value={role == "shop"} onChange={(e)=> setRole(e.target.value)}><img src={process.env.PUBLIC_URL + `/Images/shop 1.png`} /></button>
</div>
<div class="rect2">
<button class="button" type="button" value={ role == "customer"} onChange={(e)=> setRole(e.target.value)}> <img src={process.env.PUBLIC_URL + `/Images/take-away.png`} /></button>
</div>
</div>
</div>
);
}
export default Register
You should change your route from server.post("api/auth/register", (req,res)=>{ to server.post("/api/auth/register", (req,res)=>{ in server.js file

I am getting "POST http://localhost:5000/api/users 400 (Bad Request)" response while using axios.post from action in react

I am using axios.post in my auth action by which I want to post my register detail that I am getting from register component . But I am getting bad request response and with error
"Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)"
Please find the below code for my Auth action ,Register component and server code for registering users please let me know the mistake that I making here :
//auth action :
import axios from "axios";
import {setAlert} from './alerts';
import {REGISTER_FAIL,REGISTER_SUCCESS} from './types';
// Register User
export const register = ({name,email,password}) => async (dispatch) => {
const headers = {
'Content-Type': 'application/json'
}
const body=JSON.stringify({name,email,password});
console.log(body);
try {
const res = await axios.post('http://localhost:5000/api/users', body, {
headers: headers
})
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
});
} catch (err) {
const errors = err.response.data.errors;
/*
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
*/
console.log(err);
dispatch({
type: REGISTER_FAIL
});
}
};
// , "proxy": "http://localhost:5000"
// Register component
import React from 'react';
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { setAlert } from '../../actions/alerts';
import { register} from '../../actions/auth';//importing register action
import './../../App.css';
export const Register = (props) => {
const [formData, setFormData] = useState({
name:'',
email:'',
password:'',
password2:''
})
const {name,email,password,password2}={...formData};
const onChange=(e)=>setFormData({...formData,[e.target.name]:e.target.value});
const onSubmit=(e)=>{
e.preventDefault();
if(password!==password2){
props.setAlert('password do not match','danger');
}
else{
props.register({name,email,password});
}
}
return (
<div >
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Create Your Account</p>
<form className="form" onSubmit={e=>onSubmit(e)}>
<div className="form-group">
<input type="text" placeholder="Name"
name="name" value={name}
onChange={e=>onChange(e)}
required />
</div>
<div className="form-group">
<input type="email"
placeholder="Email Address"
name="email" value={email}
onChange={e=>onChange(e)} />
<small className="form-text"
>This site uses Gravatar so if you want a profile image, use a
Gravatar email</small
>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
value={password}
onChange={e=>onChange(e)}
minLength="6"
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Confirm Password"
name="password2"
value={password2}
onChange={e=>onChange(e)}
minLength="6"
/>
</div>
<input type="submit" className="btn btn-primary" value="Register" />
</form>
<p className="my-1">
Already have an account? <Link to="/login">Sign In</Link>
</p>
</div>
)
}
export default connect(null,{setAlert,register}) (Register);
Server API code :
const express =require('express');
const User=require('../../models/User');
const gravatar=require('gravatar');
const {check, validationResult}=require('express-validator');
const bcrypt=require('bcryptjs');
const jwt=require('jsonwebtoken');
const router=express.Router();
const config=require('config');
// signin
router.post('/',[
check('name','name is required').not().isEmpty(),
check('email','Need valid email').isEmail(),
check('password','length should be greater than 6').isLength({min:6})
],async(req,res)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors:errors.array()});
}
const {name,email,password}=req.body;
try{
let user= await User.findOne({email});
if(user){
return res.status(400).json({errors:'user already exist !'})
}
const avatar =gravatar.url({email})
user= new User({
name,
email,
password,
avatar
})
const salt=await bcrypt.genSalt(10);
user.password=await bcrypt.hash(password,salt);
await user.save();
const payload={
user:{
id:user.id
}
}
jwt.sign(payload,config.get('jwtsecret'),(err,token)=>{
if(err){
throw err;
}
res.json({token});
})
}
catch(err){
return res.status(400).json({errors:errors.message})
}
});
module.exports=router;

Why did it failed to load? the server responded with a status of 404 (Not Found)

I have my app(express+Next.js.MOngoDB).I signuped all my users,works Ok. Now when I try signin
http://localhost:5000/signin
I got error
Uncaught (in promise) Error: Request failed with status code 404
at createError (webpack-internal:///../../node_modules/axios/lib/core/createError.js:16)
at settle (webpack-internal:///../../node_modules/axios/lib/core/settle.js:17)
Terminal
GET /__nextjs_original-stack-frame?isServerSide=false&file=webpack-internal%3A%2F%2F%2F..%2F..%2
POSTMAN signin works fine
app.js(just API)
const app = express();
app.use('/api/v1/auth', auth);
Next.js,Signin
import SigninComponent from '../components/frontauth/SigninComponent';
const Signin = () => {
return (
<Layout>
<h2 className="text-center pt-3 pb-4">Signin</h2>
<div className="row">
<div className="col-md-6 offset-md-3">
<SigninComponent />
</div>
</div>
</Layout>
);
};
SigninComponent
/* eslint-disable no-undef */
import axios from 'axios';
import React, { useState } from 'react';
import { API } from '../../config';
const SigninComponent = () => {
const [values, setValues] = useState({
email: '',
password: ''
});
const [loading, setLoading] = useState(false);
const { email, password } = values;
const handleSubmit = async (e) => {
e.preventDefault();
const { email, password } = values;
const user = { email, password};
await axios.post(`${API}/api/v1/auth/signin`, user);
};
const handleChange = name => e => {
setValues({ ...values, error: false, [name]: e.target.value });
};
const showLoading = () => (loading ? <div className="alert alert-info">Loading...</div> : '');
const signinForm = () => {
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<input
value={values.email}
onChange={handleChange('email')}
type="email"
className="form-control"
placeholder="Type your email"
/>
</div>
<div className="form-group">
<input
value={values.password}
onChange={handleChange('password')}
type="password"
className="form-control"
placeholder="Type your password"
/>
</div>
<div>
<button className="btn btn-primary">Signin</button>
</div>
</form>
);
};
return <React.Fragment>
{showLoading()}
{signinForm()}
</React.Fragment>;
};
export default SigninComponent;
How should I edit .babelrc,I have only one line,should I add plugins?
"presets": ["next/babel"]
Why does the terminal point to SSR FALSE?

Resources