I am currently working on a React and Node project for personal learning, I used the fetch method to get data from the backend to the frontend react component and I am currently having an issue with fetching data for one of my components. In my Profile component am trying to fetch the data for a specific user and display on the component but am getting a SyntaxError: Unexpected token < in JSON at position 0
error.
I was able to debug the code with browser console and found out that my fetch call is returning an HTML page instead of the user data, I have to try tracing the code to fix the error but I can't seem to find where the error is coming from.
I have use Postman to check my backend code and everything works just fine from the backend and I was able to fetch the data correctly, other frontend components also work fine in fetching data except for the Profile component. Here my profile code and the code where the error is coming from
Profile.js
import {read} from './api-user'
import auth from './../auth/auth-helper'
import {Redirect, Link} from 'react-router-dom'
import Paper from 'material-ui/Paper'
import List, {ListItem, ListItemAvatar, ListItemText, ListItemSecondaryAction} from 'material-ui/List'
import Typography from 'material-ui/Typography'
import Person from 'material-ui-icons/Person'
import Avatar from 'material-ui/Avatar'
import Divider from 'material-ui/Divider'
import Edit from 'material-ui-icons/Edit'
import DeleteUser from '../user/DeleteUser'
import IconButton from 'material-ui/IconButton'
import PropTypes from 'prop-types'
import {withStyles} from 'material-ui/styles'
const styles = theme => ({
root: theme.mixins.gutters({
maxWidth: 600,
margin: 'auto',
padding: theme.spacing.unit * 3,
marginTop: theme.spacing.unit * 5
}),
title: {
margin: `${theme.spacing.unit * 3}px 0 ${theme.spacing.unit * 2}px`,
color: theme.palette.protectedTitle
}
})
class Profile extends React.Component {
constructor(props) {
super(props)
this.state = {
user: '',
redirectToSignin: false
}
this.init = this.init.bind(this)
}
init(userId) {
const jwt = auth.isAuthenticated()
read({userId}, {t: jwt.token}).then((data) => {
if(data.error) {
this.setState({redirectToSignin: true})
}
this.setState({user: data})
})
}
componentDidMount() {
const userId = this.props.match.params.userId
// const {match: {params}} = this.props
this.init(userId)
}
render() {
const {classes} = this.props
const {redirectToSignin, user} = this.state
if(redirectToSignin) {
return (<Redirect to="/signin"/>)
}
return (
<div>
<Paper className={classes.root} elevation={4}>
<Typography type="title" className={classes.title}>Profile</Typography>
<List dense>
<ListItem>
<ListItemAvatar>
<Avatar>
<Person/>
</Avatar>
</ListItemAvatar>
<ListItemText primary={user.name} secondary={user.email}/>
{auth.isAuthenticated().user && auth.isAuthenticated().user._id == user._id &&
(<ListItemSecondaryAction>
<Link to={'/user/edit/' + user._id}>
<IconButton aria-label="Edit" color="primary">
<Edit/>
</IconButton>
</Link>
<DeleteUser userId={user._id}/>
</ListItemSecondaryAction>)}
</ListItem>
<Divider/>
<ListItem>
<ListItemText primary={user.about} secondary={"Joined: " + (new Date(user.created).toDateString())}/>
</ListItem>
</List>
</Paper>
</div>
)
}
}
Profile.propTypes = {
classes: PropTypes.object.isRequired
}
export default withStyles(styles) (Profile)
The componentDidMount would call the init method to display the user data but the promise in the init method is returning undefine instead of a JSON object
api.user.js
const create = (user) => {
return fetch('api/users/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
}).then((res) => {
return res.json()
}).catch((err) => {
console.log(err)
})
}
const list = () => {
return fetch('api/users/', {
method: 'GET'
}).then((res) => {
return res.json()
}).catch((err) => {
console.log(err)
})
}
const read = (params, credentials) => {
return fetch(`api/users/${params.userId}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + credentials.t
}
})
.then((res) => {
return res.json()
}).catch((err) => {
console.log(err)
})
}
const update = (params, credentials, user) => {
return fetch('api/users/' + params.userId, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + credentials.t
},
body: JSON.stringify(user)
}).then((res) => {
return res.json()
}).catch((err) => {
console.log(err)
})
}
const remove = (params, credentials) => {
return fetch('api/users/' + params.userId, {
method: 'DELETE',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + credentials.t
}
}).then((res) => {
return res.json()
}).catch((err) => console.log(err))
}
export {create, list, read, update, remove}
the read function call was supposed to fetch the user data with the specified user id from the database but after fetching the data its return an HTML instead of the user data and that why that SyntaxError coming from.
I don't even know what I am spelling wrong because I have to check all the code over and over again.