Nodejs react cannot get data on frontend - javascript

I'm trying to get all user data from the backend to display on the webpage. However, the getAllUsers() seems to not send back a response as the console.logs are not printed out.
Here is my ViewUsers.js
import React, { Component } from "react";
import AdminServices from "../Services/AdminServices";
import "././ViewUsers.css"
const ViewUsersComponent = (users) => {
return (
<div className="viewusers">
<h1>All users</h1>
<div className="viewusers-list">
{users.map((user) => {
return (
<React.Fragment>
<p> <b>Name</b> : {user.username} </p>
<p> <b>Email</b> : {user.email} </p>
<p> <b>Website role</b> : {user.websiteRole} </p>
<hr />
</React.Fragment>
)
})}
</div>
</div>
)
}
export default class ViewUsers extends Component {
constructor(props) {
super(props);
this.retrieveUsers = this.retrieveUsers.bind(this);
this.state = {
users: []
}
}
componentDidMount() {
this.retrieveUsers();
}
retrieveUsers() {
AdminServices.getAllUsers()
.then(response => {
if (response && response.data) {
this.setState({
users: response.data
});
}
console.log(response.data);
console.log('DATA RECEIVED')
})
.catch(e => {
console.log('ERROR')
console.log(e);
});
}
render () {
const { users } = this.state;
console.log(users)
if (Array.isArray(users) && users.length) {
return ViewUsersComponent(users)
} else {
return (
window.location = '/notfound'
)
}
}
}
This is the AdminServices.js
import http from "../http-common"
class AdminServices {
getAllUsers() {
return http.get("/users");
}
getAllProjects() {
return http.get("/projects");
}
}
export default new AdminServices();
And the http-common.js
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8080",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
mode: "cors",
credentials: "include",
withCredentials: true
});
And the userRoute.js
const express = require('express');
const User = require('../models/user').userModel;
const userRouter = express.Router();
// get all users
userRouter.get('/', async (req, res) => {
try {
console.log("loading users")
users = await User.find();
if (users == null) {
res.status(404).json({ message: "users not found" });
}
res.send(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
When I send a get request to the user route via rest api, it works so I am not sure why it does not go through on the frontend

Please add CORS on backend project. You can configure the UI domain or use ‘*’ to allow all domain.

Related

React - Iterating through state array with no result

I'm fetching JSON data from a local express server using mongoosejs to parse mongoDB queries. I'm getting a "title" and "id" from the server, to generate a sidebar of buttons.
But my issue is that I can't seem to iterate through the state array after fetching the data from the server
The GET request handler on the server:
exports.sidebar = (req, res) => {
Note.find({}, "_id title")
.then(notes => {
console.log(notes);
res.send(notes)
}).catch(err => {
return res.status(404).send({
message: err
})
})
}
My react component. in loadData(), i fetch the data from the API. and in loadSidebarElements() I try to iterate through the state array,
import React, {Component} from "react";
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {
titleList: [],
idList: []
}
this.loadData = this.loadData.bind(this);
this.loadSidebarElements = this.loadSidebarElements.bind(this);
}
componentDidMount() {
this.loadData();
}
loadData() {
let titles = [];
let ids = [];
const requestOptions = {
method: "GET",
headers: {"Content-Type" : "application/json"},
mode: "cors"
};
fetch("http://127.0.0.1:5000/notes/sidebar", requestOptions)
.then(response => response.json())
.then(data => {
data.map(item => {
titles[titles.length] = String(item.title);
ids[ids.length] = String(item._id);
})
})
this.setState({
titleList: titles,
idList: ids
})
}
loadSidebarElements(){
console.log(this.state.titleList);
this.state.titleList.map(item => {
console.log(item);
})
this.state.titleList.forEach(item => console.log(item));
Object.keys(this.state.titleList).map((key, index) => {
console.log(this.state.titleList[key]);
})
}
render() {
return (
<div className="sidebar" style={{display: "flex", flexDirection:"column", alignItems: "center"}}>
<h1>Sidebar:</h1>
{this.loadSidebarElements()}
</div>
)
}
}
export default Sidebar;
The console output in firefox:
Console log from firefox
I obviously get the data to the server, but I just can't seem to iterate through it...

Getting 406(not acceptable error) in vuejs, vuex

I am working on a project and I am getting 406(not acceptable) error in the browser. I am using vuejs, vuex framework.
verify.vue code:
<template>
<div>
<usernav/>
<div class="container">
<h1 style="padding:90px;"> Enter OTP</h1>
<div>
<mdb-input label="OTP" v-model="value" />
<br />
<mdb-btn color="info" #click="verify()">Verify</mdb-btn>
</div>
</div>
</div>
</template>
<script>
import { mdbInput, mdbBtn } from 'mdbvue'
import usernav from './user_nav'
export default {
name: 'otp',
components: {
mdbInput,
mdbBtn,
usernav
},
data () {
return {
value: ''
}
},
methods: {
verify () {
this.$store.dispatch('VERIFY', {
otp: this.value
}).then(success => {
console.log('success')
}).catch(error => {
console.log(error)
})
}
}
}
</script>
<style scoped>
.container {
width: 500px;
}
</style>
The verify.js code:
import { isAuthenticated } from './auth'
import axios from 'axios'
export default ({
state: {
},
mutations: {
},
actions: {
VERIFY: (payload) => {
return new Promise((resolve, reject) => {
const userId = isAuthenticated().user._id
const token = isAuthenticated().token
console.log(userId)
console.log(token)
axios
.post(`https://onu-backend.herokuapp.com/api/onu/user/${userId}/verifyEmail`, payload, {
headers: {
Authorization: 'Bearer ' + token
}
}).then(response => {
if (response.status === 200) {
console.log(response)
resolve(true)
}
}).catch(error => {
reject(error)
})
})
}
}
})
The isAuthenticated code:
export const isAuthenticated = () => {
if (localStorage.getItem('auth')) {
return JSON.parse(localStorage.getItem('auth'))
}
return false
}
Error I am getting: error image
Can anyone tell me why am I getting this error? The api used in the code is cross checked with postman and is working fine. I think there some problem with sending bearer token. Please help.

axios request to DRF with JWT auth fails

I have a Django rest API with JWT auth for signup and login built with react.
When trying to log in a user I get a 403 forbidden error.
I added the csrf token to the headers of the request and I can see it in the promise when using the console, so that's not the problem here.
I just don't understand where this post is breaking
import axios from "axios";
import Cookies from "js-cookie";
var csrftoken = Cookies.get("csrftoken");
const axiosInstance = axios.create({
baseURL: "http://127.0.0.1:8000/api/",
timeout: 5000,
headers: {
HTTP_X_CSRF_TOKEN: csrftoken,
Authorization: localStorage.getItem("access_token")
? "JWT " + localStorage.getItem("access_token")
: null,
"Content-Type": "application/json",
accept: "application/json",
withCredentials: true,
},
});
axiosInstance.interceptors.response.use(
(response) => response,
(error) => {
const originalRequest = error.config;
// test for token presence, no point in sending a request if token isn't present
if (
localStorage.getItem("refresh_token") &&
error.response.status === 401 &&
error.response.statusText === "Unauthorized"
) {
const refresh_token = localStorage.getItem("refresh_token");
return axiosInstance
.post("/token/refresh/", { refresh: refresh_token })
.then((response) => {
localStorage.setItem("access_token", response.data.access);
localStorage.setItem("refresh_token", response.data.refresh);
axiosInstance.defaults.headers["Authorization"] =
"JWT " + response.data.access;
originalRequest.headers["Authorization"] =
"JWT " + response.data.access;
return axiosInstance(originalRequest);
})
.catch((err) => {
console.log(err);
});
}
// specific error handling done elsewhere
return Promise.reject({ ...error });
}
);
export default axiosInstance;
And the login component using the axios instance:
import React, { Component } from "react";
import axiosInstance from "../axiosApi";
import DjangoCSRFToken from "django-react-csrftoken";
class Login extends Component {
constructor(props) {
super(props);
this.state = { username: "", password: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
async handleSubmit(event) {
event.preventDefault();
try {
const response = await axiosInstance.post("/token/obtain/", {
username: this.state.username,
password: this.state.password,
});
axiosInstance.defaults.headers["Authorization"] =
"JWT " + response.data.access;
localStorage.setItem("access_token", response.data.access);
localStorage.setItem("refresh_token", response.data.refresh);
return response;
} catch (error) {
throw error;
}
}
render() {
return (
<div>
Login
<form onSubmit={this.handleSubmit}>
<DjangoCSRFToken />
<label>
Username:
<input
name="username"
type="text"
value={this.state.username}
onChange={this.handleChange}
/>
</label>
<label>
Password:
<input
name="password"
type="password"
value={this.state.password}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default Login;
the console when hitting submit:
Please try removing CSRF from the call. and make use of #csrf_exepmt for further information please follow this link. Django csrf_exempt using your JWT it's enough.
Example:
#csrf_exempt
def myEndpoint():
// my code

React-Native AsyncStorage

I didn't understand how to make the AsyncStorage work.
I use react-native-router-flux
Basically I have 3 pages:
FirstPage
export default class Authentication extends Component {
render() {
return (
..........
<TouchableOpacity
style ={[style.button, style.buttonOK]}
onPress={() => Actions.login() }>
<Text style={style.buttonTesto}>LOGIN</Text>
</TouchableOpacity>
<TouchableOpacity
style ={[style.button, style.buttonOK]}
onPress={() => Actions.signup() }>
<Text style={style.buttonTesto}>SIGNUP</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Login
login() {
let ctrl = true;
......
if (ctrl) {
let formdata = new FormData();
const identity = {
AppName: {
Username: this.state.username,
Password: this.state.password
}
};
formdata.append("Identity", JSON.stringify(identity));
fetch(APILINK , {
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
body: formdata
})
.then(response => response.json())
.then(responseData => {
if (responseData.Error) {
.......
} else {
global.utente = new Utente(responseData);
Actions.homepageutente();
}
})
.catch(err => alert("err:" + err));
}
}
Utente
export default class Utente {
constructor(data) {
Utente.saveUtenteLoggato(data);
this._data = data;
....
);
}
get data() {
return this._data;
}
//there is a function for the signup there//
.......
static async saveUtenteLoggato(value) {
try {
await AsyncStorage.setItem("#UtenteLoggato", JSON.stringify(value));
} catch (error) {
console.log(error.message);
}
}
static async getUtenteLoggato() {
try {
return await AsyncStorage.getItem("#UtenteLoggato");
} catch (error) {
console.log(error.message);
return null;
}
}
static async clearUtenteLoggato() {
try {
global.utente = null;
await AsyncStorage.removeItem("#UtenteLoggato");
} catch (error) {
console.log(error.message);
return null;
}
}
}
So in Utente I have created the Asyncstorage function, but I don't understand how I should do when I close the app in backgroun (for example) to maintain the login active. At the moment if I go back in the App I should do another time the Login.
How can I solve it?
EDIT
Starting page
class Starting extends Component {
constructor(props)
{
super(props)
this.state = {
loading: true
}
}
componentWillMount() {
Utente.getUtenteLoggato()
.then(dataUtenteLoggato => {
if (dataUtenteLoggato !== null) {
global.utente = new Utente(JSON.parse(dataUtenteLoggato));
} else {
Actions.authentication();
}
})
.catch(err => {
console.log(err);
})
.finally(() => {
this.setState({ loading: false });
});
}
render() {
return(
<View style={style.container}>
<Spinner visible={this.state.loading} textContent={"Loading..."} textStyle={{color: '#FFF'}} />
</View>
);
}
}
You can implement splash screen component and check auth in componentWillMount. As example - get data from AsyncStorage, then perform request to check that user is authenticated and fetch user details. If auth data(e.g. auth token) is absent in storage or server threw auth error(in case when token is invalid or expired), redirect user to login screen, else mark user as authenticated and show main screen.

React, the page does not appear

I'm trying to output an article on a new page, but the article on the new page does not appear in the console it's not there, it's empty, how can I fix it.
backend - Ruby on Rails
frontend - React/Redux
The page that displays the article.
task_details.js
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Exit from '../authentication/exit';
import { browserHistory } from 'react-router';
import { getTask } from '../../actions/tasks';
import TasksList from './tasks_list';
import Link from 'react-router'
class TaskDetails extends Component {
componentDidMount () {
let id = this.props.params.id;
this.props.onGetTask(id);
};
render() {
const { task } = this.props
console.log(this.props.location.pathname, "xxxxxxxx")
return (
<div>
{ this.props.task ?
<div className="container">
<h2 className="text-center">{task.title}</h2>
<div className="col-md-2">
<h4 className="pull-right"><i>{task.due_date}</i></h4>
</div>
<div className="clearfix"></div>
<div className="description">
<p>{task.description}</p>
</div>
</div>
:
<div className="container">
<div><h2>Not found</h2></div>
</div>
}
</div>
);
}
};
export default connect(
state => ({
task: state.tasks.item
}),
dispatch => ({
onGetTask: (id) => {
dispatch(getTask(id));
},
})
)(TaskDetails);
The page responsible for the task.
tasks.js
import axios from 'axios';
import cookie from 'react-cookies';
//const API_URL = `https://evening-taiga-79121.herokuapp.com/todos`;
const API_URL = `http://localhost:3000/todos`;
let headers = { 'Content-Type': 'application/json', };
const token = cookie.load('token');
export function fetchTasks(user_id){
return function(dispatch, getState) {
let body = JSON.stringify({ token: token });
headers['Authorization'] = `Bearer ${token}`;
axios.get(`${API_URL}`, { headers, body })
.then(res => {
if (res.status === 200) {
dispatch({ type: 'GET_TASKS', payload: res.data });
}
})
.catch(e => {
console.error("error: ", e);
})
}
}
export function getTask(id) {
return function(dispatch, getState) {
return new Promise((resolve, reject) => {
axios.get(`${API_URL}/${id}`, { headers: headers })
.then(res => {
resolve(res)
dispatch({ type: 'GET_TASK_ID', payload: res.data });
})
.catch(e => {
console.error("error: ", e);
reject(e)
})
})
}
}
export function deleteTask(id){
return function(dispatch, getState) {
let body = { token: token };
axios.delete(`${API_URL}/${id}`, { params: body, headers: headers })
.then(res => {
dispatch({ type: 'DELETE_TASK', payload: id });
})
.catch(id => {
console.error("error", id);
})
}
}
export function addTask(task){
return function(dispatch, getState) {
let body = JSON.stringify({todo: task, token: token});
console.log(body);
axios.post(API_URL, body, { headers: headers })
.then(res => {
dispatch({ type: 'ADD_TASK', payload: res.data });
})
.catch(e => {
console.error(e);
})
}
}
export function completedTask(id, complete){
return function(dispatch, getState) {
if (complete === true) {
complete = false
} else {
complete = true
}
let task = {id: id, completed: complete};
let body = {todo: task, token: token};
axios.patch(`${API_URL}/${task.id}`, body, { headers: headers })
.then(res => {
dispatch({ type: 'COMPLITED_TASK', payload: res.data });
})
.catch(e => {
console.error("error: ", e);
})
}
}
export function sortTasks(sortBy){
return function(dispatch, getState) {
let body = JSON.stringify({ token: token, sortByTitle: sortBy.title, sortByAsc: sortBy.asc });
axios.post(`${API_URL}/sort`, body, { headers: headers })
.then(res => {
console.log(res);
if (res.status === 200) {
dispatch({ type: 'SORT_BY', payload: sortBy });
dispatch({ type: 'FETCH_TODOS_SUCCESS', payload: res.data });
}
})
.catch(e => {
console.error("error: ", e);
})
}
}
export function editTask(task){
return function(dispatch, getState) {
let body = JSON.stringify({todo: task, token: token});
axios.patch(`${API_URL}/${task.id}`, body, { headers: headers })
.then(res => {
dispatch({ type: 'EDIT_TASK', payload: res.data });
})
.catch(e => {
console.error("error: ", e);
})
}
}
The page with which we go to the page with the article.
tasks_index.js
import React, {Component} from 'react';
import { Router, Route, hashHistory } from 'react-router';
import Exit from '../authentication/exit';
import TasksList from './tasks_list';
import New from './new';
import Edit from './edit';
import {connect} from 'react-redux';
import { Link } from 'react-router';
import {fetchTasks, sortTasks} from '../../actions/tasks';
const Tasks_Index = ({user_id, onFetchTasks}) => {
if (user_id) {
onFetchTasks(user_id)
return (
<div>
<div className="container">
<div className="row">
<div className="navbar-header col-md-2">
<a href="#">
<h2 className="pull-right">TASKS</h2>
</a>
</div>
<ul>
<div className="pull-right nav navbar-nav">
<h4><li className=""><Link to="/user/exit">Log out</Link></li></h4>
</div>
</ul>
</div>
</div>
<div className="container">
<div className="row">
<New />
<Edit />
<TasksList />
</div>
</div>
</div>
);
} else
return null;
}
export default connect(
state => ({
user_id: state.user.id,
editId: state.tasks.edit,
sortBy: state.tasks.sortBy
}),
dispatch => ({
onFetchTasks: (user_id) => {
dispatch(fetchTasks(user_id));
}
})
)(Tasks_Index);
Thanks for the help.

Categories