'Uncaught SyntaxError: Unexpected token <' on Login Form - reactjs

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
},
}

Related

Why isnt my pic getting displayed after using Active Storage?

I am trying to implement active storage .And have been following along with this article .Its a very very short article https://dev.to/jblengino510/uploading-files-in-a-react-rails-app-using-active-storage-201c.The backend has been set correctly as instructed...The only problem is in the front end..I am not able to write my React project code in a way thats similar to this project and hence im lacking a correct code.
Here is my Project code
The add review form card
function AddReviewForm({user,handleAddReviews}){
const params = useParams();
const[img,setImg]=useState("");
const[r,setR]=useState("");
const[imgData,setimgData]=useState("");
const newReview = {
img,
r,
imgData,
restaurant_id: params.id,
user_id: user.id,
};
const configObj = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(newReview),
};
function handleReviewSubmit(event) {
event.preventDefault();
fetch(`/reviews`, configObj)
.then((r) => r.json())
.then((review)=>{
handleAddReviews(review);
setR('')
setImg('')
setimgData('')
}
);
}
return (
<>
<h1>Add review form</h1>
<form onSubmit={handleReviewSubmit}>
<div>
<input type="file"
name="picture"
accept="image/png, image/gif, image/jpeg"
id="picture"
onChange={(e)=>setimgData(e.target.files[0])} />
</div>
<div>
<label htmlFor="r" >Review</label>
<input type="text" name="r" value={r} onChange={(e) => setR(e.target.value)} placeholder="review" />
</div>
<input type="submit" />
</form>
</>
)
}
export default AddReviewForm;
And the displayed ReviewCard.js
import { useParams } from "react-router-dom";
function ReviewCard({review,user,handleDelete}){
const{id,img,r,picture,user:reviewuser}=review
function handleDeleteClick() {
fetch(`/reviews/${review.id}`, {
method: "DELETE",
})
handleDelete(review.id)
}
return(
<>
<img src={img}/>
<img src={picture} />
<p></p>
<p>{r}</p>
<h6>By {review.user.name}</h6>
{user.id===reviewuser.id&&<button onClick={handleDeleteClick} >Delete</button>}
</>
)
}
export default ReviewCard;
Pls help me out and lemme know what changed I can do so that my picture gets displayeddd

Updating/editing username in dropdown list in react

Can anyone help me.I have been trying to learn react for while now. How do I edit/update username in react dropdown list. Lets say there is a misspelled username in the dropdown list. If I want to change or edit that username how can I do that in react. I can update everything else, except the username. Here is my code..
import React, {Component} from 'react';
import axios from 'axios';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css'
class EditExercise extends Component {
constructor(props){
super(props);
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangeDescription = this.onChangeDescription.bind(this);
this.onChangeDuration = this.onChangeDuration.bind(this);
this.onChangeDate = this.onChangeDate.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.select = React.createRef();
this.state = {
username:'',
description : '',
duration: 0,
date:new Date(),
users: []
}
}
componentDidMount(){
axios.get('http://localhost:5000/exercises/'+this.props.match.params.id)
.then(responce => {
this.setState({
username: responce.data.username,
description: responce.data.description,
duration:responce.data.duration,
date: new Date(responce.data.date)
})
})
.catch((error) =>{
console.log(error)
})
axios.get('http://localhost:5000/exercises/')
.then(responce => {
if(responce.data.length > 0){
this.setState({
users: responce.data.map(user =>user.username),
});
}
})
}
onChangeUsername(e){
this.setState({
username: e.target.value
});
}
onChangeDescription(e){
this.setState({
description: e.target.value
});
}
onChangeDuration(e){
this.setState({
duration: e.target.value
});
}
onChangeDate(date){
this.setState({
date: date
})
}
onSubmit(e){
e.preventDefault();
const exercise = {
username : this.state.username,
description: this.state.description,
duration: this.state.duration,
date: this.state.date
}
console.log(exercise);
axios.post('http://localhost:5000/exercises/update/'+this.props.match.params.id, exercise)
.then(res => console.log(res.data));
window.location ='/';
}
render() {
return (
<div>
<h3>Edit Exercise Log</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username: </label>
<select ref={this.select}
required
className="form-control"
value={this.state.username}
onChange={this.onChangeUsername}>
{
this.state.users.map((user) => {
return <option
key={user}
value={user}>{user}
</option>
})
}
</select>
</div>
<div className="form-group">
<label>Description: </label>
<input type="text"
required
className="form-control"
value={this.state.description}
onChange={this.onChangeDescription}
/>
</div>
<div className="form-group">
<label>Duration (in minutes): </label>
<input type="text"
className="form-control"
value={this.state.duration}
onChange={this.onChangeDuration}
/>
</div>
<div className="form-group">
<label>Date: </label>
<div>
<DatePicker
selected={this.state.date}
onChange={this.onChangeDate}
/>
</div>
</div>
<div className="form-group">
<input type="submit" value="Edit Exercise Log" className="btn btn-primary" />
</div>
</form>
</div>
);
}
}
export default EditExercise;
First, I see that you have a dropdown list of users that is coming from an API call. I am not entirely sure what you mean by edit the name. If the names are coming from an API and you want a user to select from a list of usernames you would need to add another JSX Input component with type text just like you do with your other fields.
My suggestion would be to add an edit icon next to the dropdown menu that onClick will setState={editUsername: true, editableUserName: this.state.username}.
This will trigger a ternary operator that renders your new component to the page (see below) below the current username Dropdown menu:
Example:
{ this.state.editUsername ?
<div className="form-group">
<label>Edit Username: </label>
<input type="text"
required
className="form-control"
value={this.state.editableUserName}
onChange={this.onUpdateUsername}
/>
<button onClick="updateUsernameInDB()">
Save Username
</button>
</div>
: null
}
onUpdateUsername will need to update another state variable called editableUserName. Then when the user clicks save call the API that can edit the username of the user. One issue here is you will need some unique identifier for your username that you are updating or you can take the easier approach by sending the original username and the new username and update it that way although that is not the most sustainable over time. Then, when the API to update the username returns 200 you should setState={editUsername: false, updatedUsername: ''}
I hope this helps.

React form submit triggers two times

I have React login form. The problem is form submit is called two times. I dont understand it. Can somebody tell me please why? Thanks a lot.
import React from "react"
import LoginErrors from "./LoginErrors"
import LoginSuccess from "./LoginSuccess"
import axios from 'axios'
import { withRouter } from "react-router-dom";
class Login extends React.Component
{
constructor(props)
{
super(props)
this.state = {
name: '',
password: '',
errors: [],
success: []
}
}
changeName = e =>
{
this.setState({name: e.target.value});
}
changePassword = e =>
{
this.setState({password: e.target.value});
}
sendData(e)
{
e.preventDefault();
this.setState({'errors': [], 'success': []});
let formData = new FormData();
formData.set('name', this.state.name);
formData.set('password', this.state.password);
axios({
method: 'POST',
url: 'http://localhost:8000/login',
data: formData,
headers: {
'Content-Type': 'text/html',
'X-Requested-With': 'XMLHttpRequest',
}
})
.then(response => {
// ? returns undefined if variable is undefined
if( response.data?.errors?.length )
{
this.setState({errors: response.data.errors})
}
if( response.data?.success?.length )
{
let data = response.data
this.props.setAccessToken(data.token)
this.props.setUserName(data.user.name)
this.props.history.push('/')
}
})
.catch(response => {
this.setState({errors: ['Login fails. Try it again later please.']})
});
}
render() {
return (
<div className="row justify-content-md-center">
<div className="col-sm-12 col-md-6">
<div id="loginForm">
<h2 className="">Login</h2>
<LoginSuccess success={this.state.success} />
<LoginErrors errors={this.state.errors} sendParentMessage={this.handleErrorsChildMessage} />
<form onSubmit={e => {this.sendData(e)}}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input ref={this.email} name="name" className="form-control" type="text" onChange={this.changeName} />
</div>
<div className="form-group">
<label htmlFor="password">Heslo</label>
<input ref={this.password} name="password" className="form-control" type="password" onChange={this.changePassword} />
</div>
<div className="form-group">
<button name="sbmt" className="btn btn-primary" type="submit">OdoslaƄ</button>
</div>
</form>
</div>
</div>
</div>
);
}
}
So the problem is in axios preflyght request which is related to the CORS policy. But How to stop it?

How do I redirect to another page on form submit?

I'm trying to redirect to a certain page once I post my form but it doesn't redirect, it only posts the form data and does not redirect to the stated page
I've tried appending the && operator in order for onSubmit to do both functions but to no avail. I also tried having both "onSubmit" and "onClick" but it's only "onSubmit" that works
//./userspost.js
import React, { Component } from "react";
import { Redirect, Link } from "react-router-dom";
import Form1 from "./form1";
import { createUsers } from "./actions/appactions";
class userspost extends Component {
state = {
redirect: false
};
setRedirect = () => {
this.setState({
redirect: true
});
};
renderRedirect = () => {
if (this.state.redirect) {
return <Redirect to="/users" />;
}
};
handleSubmit(data) {
console.log("form submission data", data);
createUsers(data);
}
render() {
return (
<div>
{this.renderRedirect()}
<Form1 onSubmit={this.handleSubmit && this.setRedirect} />
</div>
);
}
}
export default userspost;
for the posting the form data
//./form1.js
import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
const Form1 = createReactClass({
//setting initial state
getInitialState() {
return {
firstName: this.props.firstName,
lastName: this.props.lastName,
userName: this.props.userName,
role: this.props.role
};
},
handleFirstChange(e) {
this.setState({
firstName: e.target.value
});
},
handleLastChange(e) {
this.setState({
lastName: e.target.value
});
},
handleUserChange(e) {
this.setState({
userName: e.target.value
});
},
handleRoleChange(e) {
this.setState({
role: e.target.value
});
},
handleSubmit(e) {
e.preventDefault();
this.props.onSubmit(this.state);
},
render() {
return (
<form
name="categories_post"
className="form-horizontal"
onSubmit={this.handleSubmit}
>
<div id="categories_post">
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="firstName"
>
First Name
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.firstName}
onChange={this.handleFirstChange}
id="firstName"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="lastName"
>
Last Name
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.lastName}
onChange={this.handleLastChange}
id="lastName"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="userName"
>
UserName
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.userName}
onChange={this.handleUserChange}
id="userName"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="role">
Role
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.role}
onChange={this.handleRoleChange}
id="role"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<div className="col-sm-2" />
<div className="col-sm-10">
<button
type="submit"
id="categoriesSubmit"
className="btn-default btn"
>
submit
</button>
</div>
</div>
<div className="form-group">
<div className="col-sm-2" />
<div className="col-sm-10">
<button className="btn btn-danger">
<Link to="/users">Home</Link>
</button>
</div>
</div>
</div>
</form>
);
}
});
export default Form1;
for posting using the fetch API
//./actions/appactions.js
import fetch from "isomorphic-fetch";
export function createCategories(data) {
return fetch("https://localhost:44341/api/categories", {
method: "POST",
mode: "cors",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
})
.then(res => {
return res;
})
.catch(err => err);
}
export function createUsers(data) {
return fetch("https://localhost:44341/api/users/create", {
method: "POST",
mode: "cors",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
})
.then(res => {
return res;
})
.catch(err => err);
}
export function createBusiness(data) {
return fetch("https://localhost:44341/api/businesslistings/create", {
method: "POST",
mode: "cors",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
})
.then(res => {
return res;
})
.catch(err => console.log(err));
}
The issue is that you are rendering the Redirect component along with the rest of your JSX everytime. Rendering only <Redirect to="" /> should solve your problem.
class userspost extends Component {
state = {
redirect: false
};
setRedirect = () => {
this.setState({
redirect: true
});
};
handleSubmit(data) {
console.log("form submission data", data);
createUsers(data);
}
render() {
if( this.state.redirect ){
return <Redirect to="users/" />
}
return (
<div>
{this.renderRedirect()}
<Form1 onSubmit={this.handleSubmit} />
</div>
);
}
}
Also, use only the handleSubmit function in your form onSubmit event. Since adding two functions with && could cause unexpected results. And when everything is ready to redirect, just call your function setRedirect.
There is someone that already answered something similar, so I took a bit of help from there. Check it out:
https://stackoverflow.com/a/43230829/5568741

Laravel React MySQL Routing Issue

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)
})
}

Resources