Getting 406(not acceptable error) in vuejs, vuex - javascript

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.

Related

Using React UseEffect() to fetch data from GraphQL

I'm trying to fetch data from graphQL, and I know that by putting function into the react UseEffect(), I would be able to call the function once the data is updated and constructed.
However, I'm working on a chatroom, and the data does not appear on the screen:
import {
CREATE_MESSAGE_MUTATION,
MESSAGES_QUERY,
MESSAGE_SUBSCRIPTION,
} from "../graphql";
import { useQuery, useSubscription } from "#apollo/client";
import React, { useEffect } from "react";
import { Tag } from "antd";
const ChatBox = ({ me, friend, ...props }) => {
//me friend are strings
const chatBoxName = [me, friend].sort().join("_");
const { loading, error, data, subscribeToMore } = useQuery(MESSAGES_QUERY, {
variables: { name: chatBoxName },
});
useEffect(() => {
try {
subscribeToMore({
document: MESSAGE_SUBSCRIPTION,
variables: { name: chatBoxName },
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newMessage = subscriptionData.data;
console.log("Subscribing more data: ", newMessage);
},
});
} catch (e) {
console.log("Error in subscription:", e);
}
}, [subscribeToMore]);
if (loading) return <p>loading ...</p>;
if (error) return <p>Error in frontend chatbox: {error}</p>;
return (
<div className="App-messages">
{console.log(data.chatboxs[0].messages)}
{data.chatboxs[0].messages.map(({ sender: { name }, body }) => {
<p className="App-message">
<Tag color="blue">{name}</Tag>
{body}
</p>;
})}
</div>
);
};
export default ChatBox;
After a small delay of loading ..., it turns to the <div className="App-messages"> with no messages inside. However, on the console I can clearly see the messages that I want to print.
What is the problem of the function in UseEffect()? I would be so appreciated if anyone can help .
{data.chatboxs[0].messages.map(({ sender: { name }, body }) => { // <- this part
<p className="App-message">
<Tag color="blue">{name}</Tag>
{body}
</p>;
})}
As a callback, you declared a function that does not return JSX elements.
Replace with this
{data.chatboxs[0].messages.map(({ sender: { name }, body }) => (
<p className="App-message">
<Tag color="blue">{name}</Tag>
{body}
</p>;
))}

Nodejs react cannot get data on frontend

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.

I'm trying to get data when template render after authentication, but requisition returns 401 (Unauthorized)

I'm trying to get data when template render after authentication, but requisition returns 401 (Unauthorized)... when I refresh the page, the data is loaded...
When logged in:
GET http://localhost:0666/core/user/ 401 (Unauthorized)
When refresh page:
Login.vue
There's a form to submit user and password...
<script>
import { mapActions } from 'vuex'
export default {
data: () => ({
form: {
username: '',
password: ''
}
}),
components: {},
methods: {
...mapActions('auth', ['ActionDoLogin']),
async submit () {
try {
await this.ActionDoLogin(this.form)
this.$router.push({ name: 'Dashboard' })
} catch (err) {
alert(err.data ? err.data.message : 'Não foi possivel fazer login')
}
}
}
}
</script>
Dashboard.vue:
<template>
<div class="dashboard">
<a class="nav-link" style="color: #6cbde1;">Hello {{user.first_name}}, your account will expire
in 0 days</a>
</div>
</template>
<script>
import LoadSession from '../../services/loadSession'
export default {
name: 'Dashboard',
components: {},
mounted () {
LoadSession.get().then(resp => {
this.user = resp.data
})
},
data () {
return {
user: { first_name: '' }
}
},
methods: {}
}
</script>
actions.js
import services from '#/http'
import * as storage from '../storage'
import * as types from './mutation-types'
export const ActionDoLogin = async ({ dispatch }, payload) => {
await services.auth.login(payload).then(res => {
dispatch('ActionSetToken', res.data.token)
})
return await services.auth.loadSession().then(res => {
dispatch('ActionSetUser', res.data.body)
})
}
export const ActionCheckToken = ({ dispatch, state }) => {
if (state.token) {
return Promise.resolve(state.token)
}
const token = storage.getLocalToken()
if (!token) {
return Promise.reject(new Error('token Inválido'))
}
dispatch('ActionSetToken', token)
return dispatch('ActionLoadSession')
}
export const ActionLoadSession = async ({ dispatch }) => {
try {
const user = await services.auth.loadSession()
dispatch('ActionSetUser', user)
} catch (err) {
dispatch('ActionSignOut')
}
}
export const ActionSetUser = ({ commit }, payload) => {
commit(types.SET_USER, payload)
}
export const ActionSetToken = ({ commit }, payload) => {
storage.setLocalToken(payload)
storage.setHeaderToken(payload)
commit(types.SET_TOKEN, payload)
}
export const ActionSignOut = ({ dispatch }) => {
storage.setHeaderToken('')
storage.deleteLocalToken()
dispatch('ActionSetUser', {})
dispatch('ActionSetToken', '')
}
services.js
export default {
login: { method: 'post', url: 'api-token-auth/' },
loadSession: { method: 'get', url: 'core/user/' }
}
What could be causing this? Help me...
This is not the solution, but "solved" my issue.
In Login.vue I send a param p: true
<script>
import { mapActions } from 'vuex'
export default {
data: () => ({
form: {
username: '',
password: ''
}
}),
components: {},
methods: {
...mapActions('auth', ['ActionDoLogin']),
async submit () {
try {
await this.ActionDoLogin(this.form)
this.$router.push({ name: 'Dashboard', params: { p: true } })
} catch (err) {
alert(err.data ? err.data.message : 'Não foi possivel fazer login')
}
}
}
}
</script>
When the page renders, a reload is done to update the page.
Using a if condition to set p to false and reload once.
mounted () {
LoadSession.get().then(resp => {
this.user = resp.data
})
if (this.$route.params.p) {
this.$route.params.p = false
location.reload()
}
}
I'm still looking for the best solution, but for a while this is enough...

Im am getting undefined with mapstatetoprops

I am trying pass logged data from my redux actions to the front end but keep getting user.name of null or undefined.
This is the front end where I am simply trying to get user.name to appear so that it says Hi user.name(name of persons account).
import React, { Component } from "react";
import { NewPropertyForm, FormPageOne, FormPageTwo, FormPageThree,
FormPageFour } from "../../components/NewPropertyForm";
import { PropertyList } from "../../components/PropertyList";
import { Container, Button, Modal, ModalCard, ModalCardTitle,
ModalBackground, ModalCardFooter, ModalCardHeader, Delete, ModalCardBody
} from 'bloomer';
import StepZilla from "react-stepzilla";
import modal from "./modal-bg.svg";
import "./Manager.css";
import {login} from '../../actions/authActions'
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux'
const steps =
[
{name: 'Step 1', component: <FormPageOne /> },
{name: 'Step 2', component: <FormPageTwo /> },
{name: 'Step 3', component: <FormPageThree /> },
{name: 'Step 4', component: <FormPageFour /> }
]
const modalBG = { backgroundImage: `url(${modal})` }
export class Manager extends Component {
// Setting our component's initial state
state = {
modal: "",
};
modalOpen = () => {
this.setState({ modal: "is-active" })
}
modalClose = () => {
this.setState({
modal: "",
login: "",
})
}
render() {
let { user } = this.props;
return (
<div className="manager">
<Container className="manager-container">
<div className="columns">
<div className="column">
<h1 className="title">Hi {user.name}</h1>
<h2 className="sub-title">You currently have 3 properties</h2>
<h2 className="sub-title">Check out the new applications you
received.</h2>
</div>
<div className="column user-dash-right">
<Button
isColor='primary'
className=""
onClick={this.modalOpen}><p>Create Listing</p></Button>
</div>
</div>
<h1 className="title has-text-centered">My Properties</h1>
<PropertyList />
<div className="new-property-modal">
<Modal className={this.state.modal}>
<ModalBackground />
<ModalCard style={ modalBG } >
<ModalCardBody>
<Delete onClick={this.modalClose} />
<div className='step-progress'>
<StepZilla
steps={steps}
showSteps={false}
nextButtonCls="button is-medium is-primary"
backButtonCls="button is-medium is-primary"
/>
</div>
</ModalCardBody>
</ModalCard>
</Modal>
</div>
</Container>
</div>
);
}
}
const mapStateToProps = ({auth}) => ({
user: auth.user,
authError: auth.authError
});
export default connect(mapStateToProps)(Manager)
This is the actions I have setup
import API from "../utils/API";
import { IS_AUTHENTICATED, AUTHENTICATION_FAILED } from
'../constants/actionTypes';
export const signup = ({name, email, phonenumber, password, role}) =>
async dispatch => {
try {
const {data} = await API.saveUser({
name,
email,
phonenumber,
password,
role
})
dispatch({
type: IS_AUTHENTICATED,
payload: data.user
})
console.log('--success', data);
} catch(error) {
console.error(error);
console.log('Come on work damnit')
}
}
export const login = ({email, password}) => async dispatch => {
try {
const {data} = await API.loginUser({
email,
password
})
dispatch({
type: IS_AUTHENTICATED,
payload: data.user
});
console.log('--success', data.user.name);
} catch(error) {
dispatch({
type: AUTHENTICATION_FAILED,
payload: "Invalid credentials, cannot login"
});
console.error(error);
}
}
export const getAuthenticated = () => async dispatch => {
try {
const {data, error} = await API.getAuthenticated();
console.log(data);
if(data) {
dispatch({
type: IS_AUTHENTICATED,
payload: data
});
} else {
console.log('ssss', error)
}
// if(getUser) login
//else logout
} catch(error) {
//window redirect to login
}
}
export const logout = () => async dispatch => {
try {
// const revoke = await API.logout()
dispatch({
type: IS_AUTHENTICATED,
payload: null
});
//should automatically display logout nav
//or redirect to anther page
} catch(e) {
//just refresh page
}
}
and these are my reducers
import {
IS_AUTHENTICATED,
AUTHENTICATION_FAILED
} from '../constants/actionTypes';
const initialState = {
user: null
}
const authReducer = (state = initialState, {type, payload}) => {
switch(type) {
case IS_AUTHENTICATED:
return {...state, user: payload, userInfo: payload}
case AUTHENTICATION_FAILED:
return {...state, user: null, authError: payload}
default:
return state
}
}
export default authReducer;
As you can see I tried to pass user.name but i keep getting cannot read property of null if I do const { user } = this.props
and i get cannot read property of undefined if i do const { user } = this.state.
I figured it out i justed needed to add
<span>
<h1 className="title">Hi {user.name}</h1>
</span>
and it worked!

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