why giving Axios error-404 in react and laravel api - javascript

I am trying to submit data from a form on my page to a react.js api using axios but i get the following error.
import axios from 'axios';
import React, { Component } from 'react'
import { Link } from 'react-router-dom';
class AddStudent extends Component {
state = {
name:'',
course:'',
email:'',
phone:'',
}
handleInput = (e) => {
this.setState
({
[e.target.name]:e.target.value
});
}
saveStudent = async (e) =>{
e.preventDefault();
const res = await axios.post('http://127.0.0.1:8000//api/add-student',this.state);
if(res.data.status === 200)
{
console.log(res.data.message);
this.setState({
name:'',
course:'',
email:'',
phone:'',
});
}
}
render()
{
return (
<div className="container">
<div className="row">
<div className="col-md-6">
<div className="card">
<div className="card-holder">
<h4>
Add Student
<Link to={'/'} className="btn btn-primary btn-sm float-end"> Back </Link>
</h4>
</div>
<div className='card-body'>
<form onSubmit={this.saveStudent} >
<div className="form-group mb-3">
<label>Student Name</label>
<input type="text" name="name" onChange={this.handleInput} value={this.state.name} className="form-control" />
</div>
<div className="form-group mb-3">
<label>Student Course</label>
<input type="text" name="course" onChange={this.handleInput} value={this.state.course} className="form-control" />
</div>
<div className="form-group mb-3">
<label>Student Email</label>
<input type="text" name="email" onChange={this.handleInput} value={this.state.email} className="form-control" />
</div>
<div className="form-group mb-3">
<label>Student Phone</label>
<input type="text" name="phone" onChange={this.handleInput} value={this.state.phone} className="form-control" />
</div>
<div className="form-group mb-3">
<button type="submit" className="btn btn-primary">Save Student</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default AddStudent
this is my student controller data which I want to send in my dtabase but it giving error --> "AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_REQUEST" "
<?php
namespace App\Http\Controllers\Api;
use App\Models\Student;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function store(Request $request)
{
$student= new Student;
$student->name= $request-> input('name');
$student->course= $request-> input('course');
$student->email= $request-> input('email');
$student->phone= $request-> input('phone');
$student ->save();
return response()->json([
'status'=> 200,
'message'=>'Student added Successfully',
]);
}
}
here it is my .env file
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:08iFPF3lcJqA98M9d9+lUeYi88nVtkHCWk2XIV6dKBU=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelreactjs
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello#example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

I hope the mistake is in the url "http://127.0.0.1:8000//api/add-student". You have provided // after port number "8000". It has to be /. The 404 error is "Page not found" error. In case, If you get this error. You need to check whether the url is properly configured axios react or check whether the url is found in api.php in laravel.

I was using something like this
axios.get(https://jsonplaceholder.typicode.com/posts/${id})
Initially I used ('https://jsonplaceholder.typicode.com/posts/${id}'). See the changes at (' with ). I am not sure at all if this could be valid here but you can give it a try and change ' with in your Api link and try if it works.

Related

email_js__WEBPACK_IMPORTED_MODULE_2___default(...).sendForm is not a function

While I was use the Emailjs to use the email service on my portfolio website.
When i try to submit the form I get this above error..
This was the code that I used to create form, using reactjs..
If someone says about the dependencies then do refer the bellow image
the email-js dependency that was downloaded
import React from "react";
import "./contact.css";
import { useRef } from "react";
import emailjs from "email-js";
const Contact = () => {
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs
.sendForm(
"service_6kimd8c",
"template_ql7mhzc",
form.current,
"vbCjePCf6E12Qm3kB"
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
e.target.reset();
};
return (
<section className="contact" id="contact">
<h1 className="sub_heading">
Contact me <span></span>
</h1>
<form className="form" onSubmit={sendEmail} ref={form}>
<div className="field">
<input
type="email"
name="email"
id="email"
placeholder="email"
required
/>
<label htmlFor="email">Email</label>
</div>
<div className="field">
<input
type="text"
name="name"
id="name"
placeholder="name"
required
/>
<label htmlFor="name">Name</label>
</div>
<div className="field">
<textarea
name="message"
id=""
cols="30"
rows="10"
required></textarea>
</div>
<input type="submit" className="btn" value="Submit" />
</form>
</section>
);
};
export default Contact;
It looks like you are not using the suggested react package as per the official documentation. I suggest you remove the one you are using and install the described one #emailjs/browser and do:
import emailjs from '#emailjs/browser';
instead of your approach
import emailjs from "email-js";

when i use the create function using django rest framework it dosent create a new person

when i use the create function using django rest framework it dosent create a new person instead it shows an error 405 Method Not Allowed. I even tried creating new person using frontend it just dosent work.
views.py
#api_view(['POST'])
def create_person(request):
serializer = PersonSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
create.js:
const Create = () => {
let history = useHistory();
let [person, setPerson] = useState({
name:"",
about:"",
email:"",
image:"",
})
let createPerson = () => {
e.preventDefault()
fetch(`/api/person-create/`, {
method: "POST",
headers: {
"content-type": 'application/json'
},
body: JSON.stringify(person)
})
.then(setPerson({
name:"",
about:"",
email:"",
image:"",
}))
}
let handleChange = (e) => {
setPerson({...person, [e.target.id]: e.target.value});
console.log(person)
}
useEffect(() => {
console.log("correct", person);
}, [person]);
return (
<div class="container">
<div class="row justify-content-center">
<form onSubmit={(e) => createPerson(e)}>
<div>
<h2>
<button onClick={() => history.push('/')} className="btn btn-primary mt-4">
❮ Back
</button>
</h2>
<h2 className="mt-4 mb-4" style={{width: '600px'}}>
New Person
</h2>
<div className="form-group" style={{width: '600px'}}>
<label>Name</label>
<input onChange={handleChange} className="form-control" id="name" placeholder="Enter Name" value={person.name} />
</div>
<div className="form-group" style={{width: '600px'}}>
<label for="exampleInputEmail1">About</label>
<textarea style={{height: '250px'}} onChange={handleChange} className="form-control" id="about" placeholder="Tell us somthing about yourself" value={person.about} />
</div>
<div className="form-group" style={{width: '600px'}}>
<label>Email</label>
<input onChange={handleChange} className="form-control" id="email" placeholder="Enter Email" value={person.email} />
</div>
<div className="custom-file mt-3">
<input onChange={handleChange} type="file" className="custom-file-input" id="image" value={person.image} />
<label className="custom-file-label" for="customFile">Choose file</label>
</div>
<button type="submit" className="btn btn-primary mt-4">Submit</button>
</div>
</form>
</div>
</div>
)
}
export default Create
i dont understand whats wrong here. i am pretty sure about the views and dont think that it is wrong not sure about the react part tho. any help will be appreciated. Thanks

Why css file of one component interacted with the css file of another component in ReactJS? How to handle it?

I am trying to make a website template with Reactjs. In the Jumbotron section i make subscription form and in the home section User Entry form. But the css of one component interacted with another's one. How can i handle it?
[1]: https://i.stack.imgur.com/Wd4OQ.png
User EntryJs:-
import React, { Component } from 'react'
import './User Entry.css'
class Form extends Component {
initialState = {
name: "",
age: "",
job: ""
}
state = this.initialState
changeHandler = event => {
const { name, value } = event.target
this.setState({
[name]: value
})
}
render() {
const { name, job, age } = this.state
return (
<form className="form-inline">
<div className="row">
<div className="col-md-3">
<div className="form-group">
<label htmlFor="name">Name:-</label>
<input type="text"
className="form-control"
name="name"
id="name"
value={name}
autoFocus
onChange={this.changeHandler} />
</div>
</div>
<div className="col-md-3">
<div className="form-group">
<label htmlFor="age">Age:-</label>
<input type="text"
className="form-control"
name="age"
id="age"
value={age}
autoFocus
onChange={this.changeHandler} />
</div>
</div>
<div className="col-md-3">
<div className="form-group">
<label htmlFor="job">Job:-</label>
<input type="text"
className="form-control"
name="job"
id="job"
value={job}
autoFocus
onChange={this.changeHandler} />
</div>
</div>
<div className="col-md-3"></div>
</div>
</form>
)
}
}
export default Form
Header JS:-
import React, { Component } from 'react'
import './Header.css'
import { Link, withRouter } from "react-router-dom";
class Header extends Component {
constructor(props) {
super(props)
this.state = {
email: ""
}
}
submitHandler = event => {
event.preventDefault();
alert(`Subscribed Email is : ${this.state.email}`);
}
changeHandler = event => {
this.setState({
email: event.target.value
})
}
render() {
return (
// Navbar Starts
<div>
<div className="row navbar">
<Link to="/" style={{textDecoration:'none'}}><div className="col-md-2 logo">ReactApp</div></Link>
<div className="col-md-6"></div>
<Link to="/" style={{textDecoration:'none'}}> <div className="col-md-1 link"> Home</div> </Link>
<Link to="/about" style={{textDecoration:'none'}}> <div className="col-md-1 link"> About</div> </Link>
<Link to="/counter" style={{textDecoration:'none'}}> <div className="col-md-1 link"> Counter </div></Link>
<Link style={{textDecoration:'none'}}><div className="col-md-1 link">Login</div></Link>
</div>
<div className="jumbotron text-center">
<h1>React-App</h1>
<p>We specialize in <strong>Web Development</strong></p>
{/* Subscribing form starts*/}
<form className="form-inline subscribingForm" onSubmit={this.submitHandler}>
<div className="input-group">
<input type="email"
className="form-control"
value={this.state.email}
onChange={this.changeHandler}
size="80"
placeholder="Email..."
required />
<div className="input-group-btn">
<input type="submit" value="Subscribe" className="subscribingBtn" />
</div>
</div>
</form>
{/* Subscribing form closes*/}
</div>
</div>
)
}
}
export default withRouter(Header);
Where is the .css file loaded, in the root component? It probably is loaded globally and is used on every component.Better use JSS (https://cssinjs.org/?v=v10.3.0)
In general react transpiles all the css and add it in to tag.
And as result you one file css conflicts with other.
If you want to avoid this, you can use modular css.
https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/

Why won't my form submit user info to the database?

I'd like to know what's wrong in my code in terms of why it's not sending username, email and password to my database via an Axios POST request. My Laravel endpoint works fine because I verified via PostMan. I'm just struggling with the front end portion of this. What am I doing wrong and how can I fix this?
There error I'm getting on my browser says: Cannot POST /register
import React, {Component} from 'react';
import axios from "axios";
class Register extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
email: "",
password: ""
};
this.userNameHandler = this.userNameHandler.bind(this);
this.emailHandler = this.emailHandler.bind(this);
this.passwordHandler = this.passwordHandler.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
userNameHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.username);
}
emailHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.email);
}
passwordHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.password);
}
handleSubmit(e) {
const user = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}
this.setState({
username: e.target.value
});
axios.post('http://127.0.0.1:8000/api/auth/signup', user)
.then(response => {
console.log(response);
console.log(response.data);
});
}
render() {
return (
<div className="container">
<div id="login-row" className="row justify-content-center align-items-center">
<div id="login-column" className="col-md-6">
<div id="login-box" className="col-md-12">
<form id="login-form" className="form" method="post" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="username" className="text-info">Username:</label><br/>
<input type="text" name="username" id="username" className="form-control" onChange={this.userNameHandler}/>
</div>
<div className="form-group">
<label htmlFor="username" className="text-info">Email:</label><br/>
<input type="text" name="username" id="username" className="form-control" onChange={this.emailHandler}/>
</div>
<div className="form-group">
<label htmlFor="password" className="text-info">Password:</label><br/>
<input type="text" name="password" id="password" className="form-control" onChange={this.passwordHandler}/>
</div>
<div className="form-group">
<input type="submit" name="submit" className="btn btn-info btn-md"
value="Submit"/>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
export default Register;
You haven't called e.preventDefault(), so you get a regular form submission to the URL specified in the action attribute. You don't have one of those, but the default URL to submit to is the current URL.
The Ajax request gets cancelled as the browser navigates away from the current page to load a new one (which is the server saying it doesn't support POST requests to that URL).

Error while using react-router in multi step registration form

I get an error when i implement react router in my working multiple step registration form. When i click personal info link i get an error on console saying
"Uncaught TypeError: Cannot read property 'ownerName' of undefined"
"Uncaught TypeError: Cannot read property '_currentElement' of null".
Similiary when i click on Location i get same sort of errors, instead of ownerName i get error on "'city' of undefined". What might be the cause?
UPDATE: "react": "^0.14.7" and "react-router": "^2.0.0"
My Code
Index.js(entry point)
import React from 'react';
import {render} from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import assign from 'object-assign';
import Layout from './components/Layout';
let fieldValues = {
ownerName:'',
email:'',
phoneNumber:'',
city : '',
place : ''
}
class AddRent extends React.Component{
constructor(props,context) {
super(props,context);
this.state = {
step: 1
};
}
saveValues(field_value) {
return function() {
fieldValues = Object.assign({}, fieldValues, field_value)
}()
console.log('fieldValues are', fieldValues);
}
nextStep(step) {
var step = this.state.step;
var newStep = step+1;
this.setState({step:newStep});
}
previousStep(step) {
var step = this.state.step;
var newStep = step-1
this.setState({
step : newStep
});
}
showStep() {
switch (this.state.step) {
case 1:
return <RenderPersonalInfo fieldValues={fieldValues}
nextStep={this.nextStep.bind(this)}
previousStep={this.previousStep.bind(this)}
saveValues={this.saveValues.bind(this)} />
case 2:
return <RenderLocation fieldValues={fieldValues}
nextStep={this.nextStep.bind(this)}
previousStep={this.previousStep.bind(this)}
saveValues={this.saveValues.bind(this)} />
}
}
render() {
var style = {
width : (this.state.step / 2 * 100) + '%',
backgroundColor:'#000'
}
return (
<main>
<span className="progress-step">Step {this.state.step}</span>
<progress className="progress" style={style}></progress>
{this.showStep()}
</main>
)
}
}
class RenderPersonalInfo extends React.Component{
render(){
return(
<div>
<h3>Personal Information</h3>
<p className="subtitle">Provide your authentic information so rent seekers can contact you</p>
<hr/>
<div className="col-md-4">
<label htmlFor='name'>Owner Name</label>
<input ref="name" defaultValue={this.props.fieldValues.ownerName} type="textbox" className="form-control" id="name" placeholder="Owner name" />
</div>
<div className="col-md-4">
<label htmlFor="email">Email</label>
<input ref="email" defaultValue={this.props.fieldValues.email} type="email" className="form-control" id="email" placeholder="email" />
</div>
<div className="col-md-4">
<label htmlFor="phoneNumber">Phone Number</label>
<input ref="phone" defaultValue={this.props.fieldValues.phoneNumber} type="textbox" className="form-control" id="phoneNumber" placeholder="phone number" />
</div>
<hr/>
<div className="row continueBtn text-right">
<button className="btn how-it-works" ref="personalInfo" onClick={this.nextStep.bind(this)}>Continue</button>
</div>
</div>
);
}
nextStep(step){
var data = {
ownerName : this.refs.name.value,
email : this.refs.email.value,
phoneNumber: this.refs.phone.value,
}
console.log(data.ownerName);
if ((data.ownerName)&&(data.email)&&(data.phoneNumber)) {
this.props.saveValues(data);
this.props.nextStep();
}
else{
alert('please enter the name, email and phone number');
}
}
}
class RenderLocation extends React.Component{
render(){
return(
<div>
<h3>Help guests find your place</h3>
<p className="subtitle">will use this information to find a place that’s in the right spot.</p>
<hr/>
<div className="col-md-6">
<label htmlFor="city">City</label>
<input ref="city" defaultValue={this.props.fieldValues.city} type="textbox" className="form-control" id="city" placeholder="Biratnagar" />
</div>
<div className="col-md-6">
<label htmlFor="placeName">Name of Place</label>
<input ref="place" defaultValue={this.props.fieldValues.place} type="textbox" className="form-control" id="placeName" placeholder="Ganesh Chowk" />
</div><hr/>
<div className="row continueBtn">
<button className="btn how-it-works pull-left" onClick={this.props.previousStep.bind(this)}>Back</button>
<button className="btn how-it-works pull-right" onClick={this.nextStep.bind(this)}>Continue</button>
</div>
</div>
);
}
nextStep(step){
var data = {
city :this.refs.city.value,
place :this.refs.place.value,
}
if ((data.city)&&(data.place)) {
this.props.saveValues(data);
this.props.nextStep();
}
else{
alert('please enter the name of city and place');
}
}
}
render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<Route path="personal" component={RenderPersonalInfo}></Route>
<Route path="location" component={RenderLocation}></Route>
</Route>
</Router>,document.getElementById('app')
);
Layout.js
import React from 'react';
import { Link } from 'react-router';
export default class Layout extends React.Component {
render() {
return (
<div className="container-fluid">
<h1>I am Layout</h1>
<div className="row">
<div className="col-sm-4">
<ul className="list-group">
<li className="list-group"><Link to="personal">Personal Info</Link></li>
<li className="list-group"><Link to="location">Location</Link></li>
</ul>
</div>
<div className="col-sm-8">
{this.props.children}
</div>
</div>
</div>
);
}
}
You are reading this.props.fieldValues.city and a few other values from this.props in RenderLocation that you never specified. The render() method crashes because this.props.fieldValues is undefined, and you get cryptic errors as the result.
Always look at the first errors (thrown by your code).
The subsequent errors like
"Uncaught TypeError: Cannot read property 'ownerName' of undefined"
"Uncaught TypeError: Cannot read property '_currentElement' of null".
are just symptoms of React getting confused after your code throws an earlier exception.
The AddRent component that used to specify these props is not used anywhere in your code. Since router uses the router configuration to create your components, it won’t give them any custom props—you need to read this.props.params supplied by the router and figure out the current step, as well as related fieldValues, from them.

Categories

Resources