Laravel React MySQL Routing Issue - reactjs

I am trying to make it so that I can register a user but I am getting a 404 error, assuming that means that react is unable to find the route established by the api.php file, is there anything else that I am missing? I have already set it in the package.json file that the proxy is set to "localhost:8000" (the port I chose to use for laravel's backend stuff). I am confused on why it's not hitting this route upon submitting. I feel like I'm close but I am new to using php as the backend so any insight would be helpful.
I am also creating something where the user is able to play music on the app, so there is a route for that labeled "shop", and that does not work for the sole reason that I have not set that route up (also gives a 404 error).
Below are my api routes that I am trying to get react to detect
<?php
Route::post('register','UserController#register');
Route::post('login','UserController#login');
Route::post('profile','UserController#getAuthenticatedUser');
Route::middleware('auth:api')->get('/user', function(Request $request){
return $request->user();
});
?>
And this is the React portion of my registration file.
import React, { Component } from 'react';
import { register } from './UserFunctions';
class Register extends Component {
constructor() {
super()
this.state = {
first_name: '',
last_name: '',
email: '',
password: '',
errors: {},
}
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
onSubmit(e) {
e.preventDefault()
const newUser = {
name: this.state.first_name + ' ' + this.state.last_name,
email: this.state.email,
password: this.state.password
}
register(newUser).then(res => {
if (res) {
this.props.history.push('/login')
}
})
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6 mt-5 mx auto">
<form noValidate onSubmit={this.onSubmit}>
<h1 className="h3 mb-3 font-wieght-normal">
Register
</h1>
<div className="form-group">
<label htmlFor="first_name">First Name</label>
<input type="text" className="form-control" name="first_name" placeholder="Enter First Name" value={this.state.first_name} onChange={this.onChange} />
<label htmlFor="last_name">Last Name</label>
<input type="text" className="form-control" name="last_name" placeholder="Enter Last Name" value={this.state.last_name} onChange={this.onChange} />
<label htmlFor="email">Email Address</label><br />
<input type="email" className="form-control" name="email" placeholder="Enter Email" value={this.state.email} onChange={this.onChange} />
<br />
<label htmlFor="password">Desired Password</label><br />
<input type="password" className="form-control" name="password" placeholder="Enter Password" value={this.state.password} onChange={this.onChange} />
</div>
<button type="submit" className="btn btn-lg btn-primary btn-block">Register</button>
</form>
</div>
</div>
</div>
)
}
}
export default Register
I have those post routes defined, but when I press submit within my register form, I get a 404 error saying that it can't find this route.

Can you show me your
import { register } from './UserFunctions';
file so that I can see the url path defined.
Assuming this route is inside your routes/api.php
Route::group(['middleware' => 'api', 'prefix' => 'v1'], function(){
Route::post('register', 'RegisterController#index');
});
and in JS file
import axios from 'axios'
export const register = newUser => {
return axios
.post('api/v1/register', newUser,
{
headers: { 'Content-Type': 'application/json' }
})
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}

Related

How to redirect to profile page in React after submitting Login and Signup button?

Here is my code for my login page that I want to use to redirect onto a profile page:
import React, { Component } from "react";
export default class Login extends Component {
constructor(props){
super(props)
this.state = {
username: '',
password: '',
}
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
const {username, password} = this.state;
fetch('http://localhost:9000/users/login', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state),
})
.then((result) => result.json())
.then((info) => {console.log(info)})
}
render() {
return (
<div className="auth-wrapper">
<div className="auth-inner">
<form onSubmit={this.handleSubmit}>
<h3>Sign In</h3>
<div className="form-group">
<label>Username</label>
<input type="text" className="form-control" placeholder="Enter email" value={this.state.value} onChange={this.handleChange} name="username" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" name="password" className="form-control" value={this.state.value} onChange={this.handleChange} placeholder="Enter password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block">Submit</button>
<p className="forgot-password text-right">
Forgot password?
</p>
</form>
</div>
</div>
);
}
}
import React, { Component } from "react";
import { Redirect } from 'react-router';
import { withRouter } from 'react-router';
export default class SignUp extends Component {
constructor(props){
super(props)
this.state = {
firstName: '',
password: '',
username: '',
lastName: '',
email: '',
isAdmin: 'false',
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state.email)
console.log(this.state.isAdmin)
}
onSubmit = async (e) => {
e.preventDefault();
await this.state.isAdmin == "on" ? this.setState({isAdmin: true}) : this.setState({isAdmin: false})
// const {firstName, lastName, email,} = this.state;
fetch('http://localhost:9000/users/new', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state)
})
.then((info) => {console.log(info)})
this.props.history.push('/profile');
}
render() {
return (
<div className="auth-wrapper">
<div className="auth-inner">
<form method='POST' action='http://localhost:9000/users/new'>
<h3>Sign Up</h3>
<div className="form-group">
<label>First name</label>
<input type="text" className="form-control" placeholder="First name" name ="firstName"/>
</div>
<div className="form-group">
<label>Last name</label>
<input type="text" className="form-control" placeholder="Last name" name="lastName" />
</div>
<div className="form-group">
<label>Username</label>
<input type="text" className="form-control" placeholder="Username" name="username" />
</div>
<div className="form-group">
<label>Email address</label>
<input type="email" className="form-control" placeholder="Enter email" name="email" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" name="password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" onClick={console.log(this.state.value)} name="isAdmin" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Signup as Reviewer</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block">Sign Up</button>
<p className="forgot-password text-right">
Already registered sign in?
</p>
</form>
</div>
</div>
);
}
}
When I click my profile page I want to redirect to /profile. At the moment it hangs and successfully logs in the user. I have to manually go to /profile to reach the page right now
I am using Express as my backend FYI
Edit: I have added my sign up page code as that is not working also and not sure why. Like the login page it hangs
try this
fetch('http://localhost:9000/users/login', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state),
})
.then((result) => {
result.json();
this.props.history.push("/Profile");})
.then((info) => {console.log(info)})

authentication log in form with jwt and react

I have made and fetched a Login form with JWT and react. I managed to fetched the data for the username and password and everything works perfectly but then I want to redirect the user to a new page when he clicks on submit and I have no idea how to do that. I'm also using react router. Any help will be welcome
import React, { Component } from "react";
import axios from "axios";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: "test",
password: "test",
}
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
})
}
login = () => {
const {username, password} = this.state;
axios(`/users/login`, {
method: "POST",
data: {
username,
password,
}
})
.then(response => {
localStorage.setItem('token', response.data.token);
console.log(response);
})
.catch(error => {
console.log(error)
})
}
render() {
return (
<div className="log">
<h3>Sign In</h3>
<div className="form-group">
<label>Username</label>
<input type="username" className="form-control" placeholder="Enter username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" name="password" value={this.state.password} onChange={this.handleChange} />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block" onClick={this.login}>Submit</button>
<p className="forgot-password text-right">
Forgot password?
</p>
</div>
);
}
}
import withRouter import {withRouter} from 'react-router-dom';
remove export before class Login class Login extends Component {...
export class at the end of the file: export default withRouter(Login);
and use react-router-dom:
axios(`/users/login`, {
//...
})
.then(response => {
localStorage.setItem('token', response.data.token);
console.log(response);
this.props.history.push('/url');
})
//...

React authentication not able to redirect to the right page

So,
I am trying to redirect the user to /home if the authentication is successful and it is.
however the user is redirected to
/?username=myusername#gmail.com&password=password
on the console log, it prints
Navigated to http://localhost:3000/?username=myusername#gmail.com&password=password
I am not sure why it does that, and what part of the code is controlling that. I didn't start the project.
I looked everywhere and it does not make sens. any one can point it out to me please?
Thanks
imports....
class Login extends Component {
constructor() {
super();
this.state = {
username: '',
password: '',
errors: {}
};
//binding functions
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
//bind state var with input value
onChange(e){this.setState({[e.target.name]: e.target.value})}
onSubmit(e) {
const user = {
username: this.state.username,
password: this.state.password
}
async function authenticate() {
.....
.....
.....
return data;
}
if (user.username.length === 0 || user.password.length === 0) {
notify.show("Access failure with insufficient or empty credentials", "custom", 500, myColor)
console.log("Access failure with insufficient or empty credentials")
} else {
authenticate()
.then(response =>{
console.log(response)
if (response.data.data!==0) {
console.log("--------------------------------")
//set the sessionStorage login
//sessionStorage.setItem("email_logged_in",user.username);
e.preventDefault();
this.props.history.push({
//redirect to home page
pathname : '/home',
state :user.username
})
}else{
//show failed notification
notify.show("login failed ! ", "custom", 500000, myColor)
}
})
//handle errors
.catch(err => {
notify.show('Error Authenticating ', "custom", 500000, myColor)
})
}
}
//rendering the login component
render() {
return (
<div className="container shadow component rounded col-sm-10 col-md-6 p-5 my-5">
<Notifications />
<div className="row">
<div className="col-md-8 mx-auto">
{/* Login Form*/}
<form noValidate onSubmit={this.onSubmit}>
<h1 className="h3 mb-3 font-weight-normal h1 text-center">Please sign in</h1>
<div className="form-group">
<label htmlFor="username">username </label>
<input
autoComplete="off"
type="username"
className="form-control form-styling"
name="username"
placeholder="Enter username"
value={this.state.username}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
autoComplete="off"
type="password"
className="form-control form-styling"
name="password"
placeholder="Password"
value={this.state.password}
onChange={this.onChange}
/>
</div>
<button
type="submit"
className="btn btn-lg btn-block btn-signin btn-animate col-md-6 col-sm-8 col-sm-2 offset-md-3 "
>
Sing in
</button>
</form>
{/*End Login Form*/}
</div>
</div>
</div>
)
}
}
export default Login
You aren't preventing the browser from handling the form submit.
You don't call e.preventDefault() until you've had a response from your authenticate call, at which point the browser will have already processed the form. The form, in this case having no action or method properties set, defaults to a GET request on the current URL passing the fields of the form, thus resulting in:
/?username=myusername#gmail.com&password=password
When handling form submissions asynchronously, you should cancel the default browser behaviour as early as possible to avoid any unexpected behaviour e.g.
onSubmit(e) {
e.preventDefault();
// do AJAX form post
}

axios put request in react is returning empty

I'm pretty new with React and Call requests. I'm building a full stack app using React, express, MySql, and Sequelize.
Everything works fine except for the Put request to edit the client information. I'm using Axios to make those calls and I can add, see, and delete data from the app but the edit part is not working.
When hitting the submit button on the form, the Put request is returning an empty array instead of the actual modified data. My routes are Ok (I believe), as testing it with Postman work just fine. I'm almost sure that my problem is on the method being used in the axios call, but I can't just find the right way to make it work. Any help would be highly appreciated.
import React, { Component } from 'react';
import axios from 'axios';
import API from '../../utils/API';
class index extends Component {
constructor(props) {
super(props);
this.onChangeLastName = this.onChangeLastName.bind(this);
this.onChangeFirstName = this.onChangeFirstName.bind(this);
this.onChangePhone = this.onChangePhone.bind(this);
this.onChangePetName = this.onChangePetName.bind(this);
this.onChangeBreed = this.onChangeBreed.bind(this);
this.onChangeNotes = this.onChangeNotes.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
client: null
}
}
componentDidMount() {
let id = this.props.match.params.id
API.getClient(id)
.then(res => {
this.setState({
client: res.data
})
console.log(this.state.client.id)
})
.catch(error => console.log(error))
}
onChangeLastName(e) {
this.setState({
lastName: e.target.value
});
}
onChangeFirstName(e) {
this.setState({
firstName: e.target.value
});
}
onChangePhone(e) {
this.setState({
phone: e.target.value
});
}
onChangePetName(e) {
this.setState({
petName: e.target.value
});
}
onChangeBreed(e) {
this.setState({
breed: e.target.value
});
}
onChangeNotes(e) {
this.setState({
notes: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
let obj = {
lastName: this.state.client.lastName.value,
firstName: this.state.client.firstName.value,
phone: this.state.client.phone.value,
petName: this.state.client.petName.value,
breed: this.state.client.breed.value,
notes: this.state.client.notes.value
};
let id = this.state.client.id
axios.put("http://localhost:3000/api/clients/" + id, obj)
// .then(alert("client Updated"))
.then(res => console.log(res))
.catch(error => console.log(error))
this.props.history.push('/admin');
}
render() {
const client = this.state.client ? (
<div className="client">
<h3 style={{ marginLeft: "60px" }}>Update Client</h3>
<form onSubmit={this.onSubmit} style={{ padding: "60px" }}>
<div className="form-group">
<label>Last Name: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.lastName}
onChange={this.onChangeLastName}
/>
</div>
<div className="form-group">
<label>First Name: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.firstName}
onChange={this.onChangeFirstName}
/>
</div>
<div className="form-group">
<label>Phone: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.phone}
onChange={this.onChangePhone}
/>
</div>
<div className="form-group">
<label>Pet Name: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.petName}
onChange={this.onChangePetName}
/>
</div>
<div className="form-group">
<label>Breed: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.breed}
onChange={this.onChangeBreed}
/>
</div>
<div className="form-group">
<label>Notes: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.notes}
onChange={this.onChangeNotes}
/>
</div>
<br />
<div className="form-group">
<input type="submit" value="Update Client"
className="btn btn-primary" />
</div>
</form>
</div>
) : (
<div className="center">Loading Client</div>
)
return (
<div className="container">
{client}
</div>
)
}
}
export default index;
I am assuming it is because of the way you are handling the onchange of your inputs. You want to set the onchange to the client value in your state. But instead you are setting it to the state itself. So then when you are building your object to send to the backend you are sending null data because you haven't set any data to the actual client value in your state and it is still null. Try console logging the state and you will see what I'm talking about. Also you are adding a .value to the end each of the state values you are trying to build your object with and this is not necessary. Finally you don't need to specify an onchange for each input just give the input a name attribute and you can set your onchange handler like so:
onChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
so your component would look something like the following:
import React, { Component } from 'react';
import axios from 'axios';
import API from '../../utils/API';
class index extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
client: null
}
}
componentDidMount() {
let id = this.props.match.params.id
API.getClient(id)
.then(res => {
this.setState({
client: res.data
})
console.log(this.state.client.id)
})
.catch(error => console.log(error))
}
onChange(e) {
this.setState({
client: {
...this.state.client,
[e.target.name]: e.target.value
}
});
}
onSubmit(e) {
e.preventDefault();
let obj = {
lastName: this.state.client.lastName,
firstName: this.state.client.firstName,
phone: this.state.client.phone,
petName: this.state.client.petName,
breed: this.state.client.breed,
notes: this.state.client.notes
};
let id = this.state.client.id
axios.put("http://localhost:3000/api/clients/" + id, obj)
// .then(alert("client Updated"))
.then(res => console.log(res))
.catch(error => console.log(error))
this.props.history.push('/admin');
}
render() {
const client = this.state.client ? (
<div className="client">
<h3 style={{ marginLeft: "60px" }}>Update Client</h3>
<form onSubmit={this.onSubmit} style={{ padding: "60px" }}>
<div className="form-group">
<label>Last Name: </label>
<input type="text"
name="lastName"
className="form-control"
defaultValue={this.state.client.lastName}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>First Name: </label>
<input type="text"
name="firstName"
className="form-control"
defaultValue={this.state.client.firstName}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Phone: </label>
<input type="text"
name="phone"
className="form-control"
defaultValue={this.state.client.phone}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Pet Name: </label>
<input type="text"
name="petName"
className="form-control"
defaultValue={this.state.client.petName}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Breed: </label>
<input type="text"
name="breed"
className="form-control"
defaultValue={this.state.client.breed}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Notes: </label>
<input type="text"
name="notes"
className="form-control"
defaultValue={this.state.client.notes}
onChange={this.onChange}
/>
</div>
<br />
<div className="form-group">
<input type="submit" value="Update Client"
className="btn btn-primary" />
</div>
</form>
</div>
) : (
<div className="center">Loading Client</div>
)
return (
<div className="container">
{client}
</div>
)
}
}
export default index;
It could be because you're calling this.props.history.push immediately after calling axios.post, essentially redirecting before the POST request has a chance to return a response.
Try putting this.props.history.push('/admin') inside the .then().
You are doing multiple thing wrong here,
For every input you should have only 1 onChange handler, every input have name attribute to work with state. For example,
<input type="text"
className="form-control"
defaultValue={this.state.client.lastName}
name="lastName" //Like this should add name for every input like below
onChange={this.onChangeHandler} //This is a common onChangeHandler for every input should add in every input like below
/>
<input type="text"
className="form-control"
defaultValue={this.state.client.firstName}
name="firstName"
onChange={this.onChangeHandler}
/>
And onChangeHandler function should be,
onChangeHandler(e){
this.setState({
...this.state.client,
[e.target.name]:e.target.value
})
}
And finally your onSubmit function should be,
onSubmit(e) {
e.preventDefault();
let obj = {
lastName: this.state.client.lastName, //Remove `.value` as we are getting values from state and not directly from input
firstName: this.state.client.firstName,
phone: this.state.client.phone,
petName: this.state.client.petName,
breed: this.state.client.breed,
notes: this.state.client.notes
};
let id = this.state.client.id
axios.put("http://localhost:3000/api/clients/" + id, obj)
// .then(alert("client Updated"))
.then(res => console.log(res))
.catch(error => console.log(error))
this.props.history.push('/admin');
}
Note: You won't get value here in console.log,
API.getClient(id)
.then(res => {
this.setState({
client: res.data
})
console.log(this.state.client.id)
})
beacuse seState is async, you should use callback in setState to make console.log,
API.getClient(id)
.then(res => {
this.setState({
client: res.data
}, () => console.log(this.state.client.id)) //This is callback
})

'Uncaught SyntaxError: Unexpected token <' on Login Form

In my NextJS app.I'm developing a login page and now I'm getting the following error.
Uncaught SyntaxError: Unexpected token <
This was not appearing before and it started appearing yesterday.I googled the error message and browsed through many SO answers but none of them were helpful.I removed all form related onSubmit and onChange code but the error is still there.Since which code causes this error,I will post entire Login component here.
import React, { Component } from 'react';
import Heading from '../components/Heading';
class Login extends Component{
constructor(props) {
super(props);
this.onChangeInput = this.onChangeInput.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
date: new Date().toJSON().slice(0,10),
username: '',
password: ''
}
}
onChangeInput(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
const t = {
date: new Date().toJSON().slice(0,10),
username: this.state.username,
password: this.state.password
}
fetch('/server', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify(this.state)
})
this.setState({
username: '',
password: ''
});
}
render(){
return(
<div>
<div style={{textAlign: "center"}}>
<h1>PackMasters Ceylon (Pvt) Ltd</h1>
<h2>Inventory Management System</h2>
<h3>Login</h3>
</div>
<form onSubmit={this.onSubmit} onChange={this.onChangeInput} className={"col-md-4 col-md-offset-4"}>
<Heading title="Login | PackMasters Ceylon (Pvt) Ltd" />
<div className={"form-group"}>
<label htmlFor="username">Username</label>
<input type="text" name="username" value={this.state.username} className={"form-control"} id="username"/>
</div>
<div className={"form-group"}>
<label htmlFor="passsword">Password</label>
<input type="password" name="password" value={this.state.password} className={"form-control"} id="password" />
</div>
<div className={"form-group"}>
<input type="submit" className={"form-control"} value="Log In"/>
</div>
</form>
</div>
);
}
}
export default Login;
After struggling a lot, I found out that it is caused by the browser cache.The problem was solved after clearing browser cache on Chrome.Still I'm not able to explain the exact reason for that.However I will mention here how to clear cache on Google Chrome.
On your computer, open Chrome.
At the top right, click More.
Click More tools > Clear browsing data.
At the top, choose a time range. To delete everything, select All time.
Next to "Cookies and other site data" and "Cached images and files," check the boxes.
Click Clear data
A few issues:
The change handler should go on each input, not on the form
A bad idea to set the timestamp in the constructor... Seems you were already going in the right direction...
If you convert the handlers into arrow functions (no this context) no need to bind in the constructor (that's just a side note...)
Try this:
import React, { Component } from 'react';
import Heading from '../components/Heading';
class Login extends Component {
state = { username: '', password: '' };
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
const user = {
date: new Date().toJSON().slice(0, 10),
username: this.state.username,
password: this.state.password,
};
fetch('/server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
});
this.setState({ username: '', password: '' });
};
render() {
return (
<div>
<div style={{ textAlign: 'center' }}>
<h1>PackMasters Ceylon (Pvt) Ltd</h1>
<h2>Inventory Management System</h2>
<h3>Login</h3>
</div>
<form
onSubmit={this.handleSubmit}
className={'col-md-4 col-md-offset-4'}
>
<Heading title="Login | PackMasters Ceylon (Pvt) Ltd" />
<div className={'form-group'}>
<label htmlFor="username">Username</label>
<input
type="text"
name="username"
value={this.state.username}
className={'form-control'}
id="username"
onChange={this.handleChange}
/>
</div>
<div className={'form-group'}>
<label htmlFor="passsword">Password</label>
<input
type="password"
name="password"
value={this.state.password}
className={'form-control'}
id="password"
onChange={this.handleChange}
/>
</div>
<div className={'form-group'}>
<input type="submit" className={'form-control'} value="Log In" />
</div>
</form>
</div>
);
}
}
export default Login;
Edit: Add a then and a catch block to fetch:
fetch('/server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
Also, I noticed you are using Next.js... You need to install Isomorphic Unfetch https://github.com/developit/unfetch/tree/master/packages/isomorphic-unfetch
In my case, static files were not being served due to global authentication enabled. which was also authenticating static files. So I had to apply #Public() metadata to that route to allow into JwtAuthGuard.
#Public()
#Get('/_next/static/*')
async getStaticContent(
#Req() req: IncomingMessage,
#Res() res: ServerResponse,
) {
await this.appService.handler(req, res);
}
More details on public metadata below.
https://docs.nestjs.com/security/authentication#enable-authentication-globally
And make sure your "esversion":6 is 6 for that follow below flow
For Mac VSCode : Code(Left top corner) => Prefrences => Settings => USER SETTINGS. and check at right side and write below Code
{
"workbench.colorTheme": "Visual Studio Dark",
"git.ignoreMissingGitWarning": true,
"window.zoomLevel": 0,
// you want to write below code for that
"jshint.options": {
"esversion":6
},
}

Resources