Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Authentication Implementing Basic Authentication Implement Sign In

signin 401 error

I keep getting a 401 unauthorized error for the sign-in.I have compared my code with the lesson and can't find any difference, please advice

` // context const value = { data: this.data, actions: { signIn: this.signIn, }, };

// user sign in

submit = () => { const { context } = this.props; const { username, password } = this.state; context.actions .signIn(username, password) .then((user) => { if (user === null) { this.setState(() => { return { errors: ["Sign-in was unsuccessful"] }; }); } else { this.props.history.push("/authenticated"); console.log(SUCCESS! ${username} is now signed in!); } }) .catch((err) => { console.log(err); this.props.history.push("/error"); }); };

cancel = () => { this.props.history.push("/"); };

// get user

async getUser() { const response = await this.api(/users, "GET", null, true, { username, password, }); if (response.status === 200) { return response.json().then((data) => data); } else if (response.status === 401) { return null; } else { throw new Error(); } } `

2 Answers

Gurbakhash Sandhu
.a{fill-rule:evenodd;}techdegree seal-36
Gurbakhash Sandhu
Web Development Techdegree Graduate 18,250 Points

I doubt this will help now but I had the same issue and for me the reason was in the Data.js file for the async getUsers() function I forgot to add the parameters for username and password so it should look like the following:

async getUser(username, password) { ... }

After adding this and restarting the client and the api my issue was resolved. Hope this helps anyone in the future!

Josh Date
.a{fill-rule:evenodd;}techdegree seal-36
Josh Date
Full Stack JavaScript Techdegree Graduate 17,973 Points

I got the same error. Not sure if you fixed it already but the reason I was getting that error was that in the Data.js file at the sign-in function, I was passing in the username and password object wrong. I had: {username, password} instead of {username: username.value, password: password.value}. I hope this helps!