You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
By clicking “Sign up for GitHub”, you agree to our
terms of service
and
privacy statement
. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
At the moment, i am trying to post a request to the server but, it keeps telling me bad request..., and i have rechecked my code through, and i do not know what the issue is......cos i am following a tutorial as a newbie in "react"......
the error from my terminal reads.....
SyntaxError: Unexpected token D in JSON at position 0
[0] at JSON.parse (),
the error from developer tools reads......
POST
http://localhost:3000/api/users
400 xhr.js:166 (Bad Request)
Pls I need help...?
below is the code taking from different folders...//
import React, { useReducer } from "react";
import axios from "axios";
import AuthContext from "./authContext";
import authReducer from "./authReducer";
import setAuthToken from "../../utils/setAuthToken";
import {
REGISTER_SUCCESS,
REGISTER_FAIL,
USER_LOADED,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT,
CLEAR_ERRORS
} from "../types";
const AuthState = props => {
const initialState = {
token: localStorage.getItem("token"),
isAuthenticated: null,
loading: true,
user: null,
error: null
const [state, dispatch] = useReducer(authReducer, initialState);
// Register User
const register = async formData => {
const config = {
headers: {
"Content-Type": "application/json"
try {
const res = await axios.post("/api/users", formData, config);
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
loadUser();
} catch (error) {
dispatch({
type: REGISTER_FAIL,
payload: error.response.data.msg
// FROM MY AUTH REDUCER FOLDER:
import {
REGISTER_SUCCESS,
REGISTER_FAIL,
USER_LOADED,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT,
CLEAR_ERRORS
} from "../types";
export default (state, action) => {
switch (action.type) {
case USER_LOADED:
return {
...state,
isAuthenticated: true,
loading: false,
user: action.payload
case REGISTER_SUCCESS:
localStorage.setItem("token", action.payload.token);
return {
...state,
...action.payload,
isAuthenticated: true,
loading: false
case REGISTER_FAIL:
localStorage.removeItem("token");
return {
...state,
token: null,
isAuthenticated: false,
loading: false,
user: null,
error: action.payload
// FROM MY ROUTE USERS FOLDER:
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("config");
// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require("express-validator");
const User = require("../models/User");
//
@route
POST api/users
//
@desc
register a user
//
@access
Public
router.post(
check("name", "Name is required")
.not()
.isEmpty(),
check("email", "Please Include a Valid Email").isEmail(),
check(
"password",
"Please Enter Password with 5 or more characters"
).isLength({ min: 5 })
async (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
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({ msg: "User Already Exists" });
user = new User({ name, email, password });
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"),
expiresIn: 360000
(error, token) => {
if (error) throw error;
res.json({ token });
} catch (error) {
console.error(error.message);
res.status(500).send("Server Error");
module.exports = router;
You have not posted what you are sending in formData. you might be having some syntax error in formData object.
if your issue still not resolved please update it with formData or close this.
________________________________
From: Yash Rathore <
[email protected]>
Sent: Monday, October 7, 2019 8:41:38 AM
To: axios/axios <
[email protected]>
Cc: IkennaU <
[email protected]>; Author <
[email protected]>
Subject: Re: [axios/axios] (400) Bad Request..... xhr 166, (
#2450
)
You have not posted what you are sending in formData. you might be having some syntax error in formData object.
if your issue still not resolved please update it with formData or close this.
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub<
#2450
?email_source=notifications&email_token=AMCLHPSQJCSTJLYK6EPEI2TQNLR3FA5CNFSM4I54KH62YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEAPJZAI#issuecomment-538877057>, or mute the thread<
https://github.com/notifications/unsubscribe-auth/AMCLHPS6JDKL3CXNVBZTV23QNLR3FANCNFSM4I54KH6Q
>.
@contactyash yash rathore...
this is the form i am posting.......trying to register a new individual and post to the server
import React, { useState, useContext, useEffect } from "react";
import AlertContext from "../../context/alert/alertContext";
import AuthContext from "../../context/auth/authContext";
const Register = props => {
const alertContext = useContext(AlertContext);
const authContext = useContext(AuthContext);
const { setAlert } = alertContext;
const { register, error, clearErrors, isAuthenticated } = authContext;
useEffect(() => {
if (isAuthenticated) {
props.history.push("/");
if (error === "User already exists") {
setAlert(error, "danger");
clearErrors();
// eslint-disable-next-line
}, [error, isAuthenticated, props.history]);
const [user, setUser] = useState({
name: "",
email: "",
password: "",
password2: ""
const { name, email, password, password2 } = user;
const onChange = e => setUser({ ...user, [e.target.name]: e.target.value });
const onSubmit = e => {
e.preventDefault();
if (name === "" || email === "" || password === "") {
setAlert("Please Enter Required Fields", "danger");
} else if (password !== password2) {
setAlert("Password do not MATCH", "danger");
} else {
register(name, email, password);
return (
Account
Register
Email Address
Password
Confirm Password