i have integrated nodejs backend to reactjs front end - node.js

hi i have integrated nodejs backend to reactjs front end. i have done these ways. but it shows error . i am new to react pls help.
function Register() {
const [data, setData] = useState({
name: "",
phone: "",
password: "",
confirmpassword: "",
});
const InputEvent = (event) => {
const { name, value } = event.target;
setData((preVal) => {
return {
...preVal,
[name]: value,
};
});
};
const formSubmit = (e) => {
e.preventDefault();
const registered = {
name: "data.name",
phone: "data.phone",
password: "data.password",
};
const isValid = formValidation();
if (isValid) {
//if form is valid, route
axios
.post(`https://localhost:5000/api/v1/auth/register/`, registered)
.then((res) => {
console.log(res);
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
history.push("/myvehicles" );
}
};
return (
<div className="signup__container">
<form className="register__form" onSubmit={formSubmit}>
<h5 className="h5__form"> Name</h5>
<input
type="text"
placeholder="पुरा नाम लेख्नुहोस्"
name="name"
value={data.name}
onChange={InputEvent}
/>
);
})}
<h5 className="h5__form"> phone </h5>
<input
type="text"
placeholder="फोन लेख्नुहोस्"
name="phone"
value={data.phone}
onChange={InputEvent}
/>
);
})}
<h5 className="h5__form"> Password </h5>
<input
type="Password"
placeholder="पासवर्ड लेख्नुहोस्s"
name="password"
value={data.password}
onChange={InputEvent}
/>
);
})}
<h5 className="h5__form"> Confirm Password </h5>
<input
type="Password"
placeholder="पुन: पासवर्ड लेख्नुहोस्"
name="confirmpassword"
value={data.confirmpassword}
onChange={InputEvent}
/>
);
})}
<p>
<button type="submit" className="signup__registerButton">
Register Now
</button>
</p>
</form>
</div>
);
}
export default Register;
the code is as above when i run both backend and front end server and post values from UI. it gives error. the error comes from the post function. if i am doing wrong pls correct.

You can remove double quotes because you pass the wrong parameters and http instead of https in your api url.
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [data, setData] = useState({
name: "",
phone: "",
password: "",
confirmpassword: ""
});
const InputEvent = (event) => {
const { name, value } = event.target;
setData((preVal) => {
return {
...preVal,
[name]: value
};
});
};
const formSubmit = (e) => {
e.preventDefault();
const registered = {
name: data.name,
phone: data.phone,
password: data.password
};
const isValid = formValidation();
if (isValid) {
//if form is valid, route
axios
.post(`http://localhost:5000/api/v1/auth/register/`, registered)
.then((res) => {
console.log(res);
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
// history.push("/myvehicles" );
}
};
return (
<div className="signup__container">
<form className="register__form" onSubmit={formSubmit}>
<h5 className="h5__form"> Name</h5>
<input
type="text"
placeholder="पुरा नाम लेख्नुहोस्"
name="name"
value={data.name}
onChange={InputEvent}
/>
<h5 className="h5__form"> phone </h5>
<input
type="text"
placeholder="फोन लेख्नुहोस्"
name="phone"
value={data.phone}
onChange={InputEvent}
/>
<h5 className="h5__form"> Password </h5>
<input
type="Password"
placeholder="पासवर्ड लेख्नुहोस्s"
name="password"
value={data.password}
onChange={InputEvent}
/>
<h5 className="h5__form"> Confirm Password </h5>
<input
type="Password"
placeholder="पुन: पासवर्ड लेख्नुहोस्"
name="confirmpassword"
value={data.confirmpassword}
onChange={InputEvent}
/>
<p>
<button type="submit" className="signup__registerButton">
Register Now
</button>
</p>
</form>
</div>
);
}

Firstly, try to post errors in the question itself
your code seems quite complicated for just a simple form submission
const registered = {
name: data.name,
phone: data.phone,
password: data.password,
};
Here data.name was string
For 400 bad request, check your node application have you defined any headers or any particular format, something like this you need to send
const article = { title: 'React POST Request Example' };
const headers = {
'Authorization': 'Bearer my-token',
'Content-Type': 'application/json'
};
axios.post('https://reqres.in/api/articles', article, { headers })
.then(response => this.setState({ articleId: response.data.id }));
}
Also, for httpsSSL issue means it is expecting Secure Certificate (as you cant hit https without its certificate- which is for encrypt-decrypt ) whereas for localhost try http even if getting error try your ip address and port (usually 8080)on which app is running on backend
shows while running the server on terminal itself
for pc ip address -> go to cmd-> type ipconfig

Related

I am getting "POST http://localhost:5000/api/users 400 (Bad Request)" response while using axios.post from action in react

I am using axios.post in my auth action by which I want to post my register detail that I am getting from register component . But I am getting bad request response and with error
"Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)"
Please find the below code for my Auth action ,Register component and server code for registering users please let me know the mistake that I making here :
//auth action :
import axios from "axios";
import {setAlert} from './alerts';
import {REGISTER_FAIL,REGISTER_SUCCESS} from './types';
// Register User
export const register = ({name,email,password}) => async (dispatch) => {
const headers = {
'Content-Type': 'application/json'
}
const body=JSON.stringify({name,email,password});
console.log(body);
try {
const res = await axios.post('http://localhost:5000/api/users', body, {
headers: headers
})
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
});
} catch (err) {
const errors = err.response.data.errors;
/*
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
*/
console.log(err);
dispatch({
type: REGISTER_FAIL
});
}
};
// , "proxy": "http://localhost:5000"
// Register component
import React from 'react';
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { setAlert } from '../../actions/alerts';
import { register} from '../../actions/auth';//importing register action
import './../../App.css';
export const Register = (props) => {
const [formData, setFormData] = useState({
name:'',
email:'',
password:'',
password2:''
})
const {name,email,password,password2}={...formData};
const onChange=(e)=>setFormData({...formData,[e.target.name]:e.target.value});
const onSubmit=(e)=>{
e.preventDefault();
if(password!==password2){
props.setAlert('password do not match','danger');
}
else{
props.register({name,email,password});
}
}
return (
<div >
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Create Your Account</p>
<form className="form" onSubmit={e=>onSubmit(e)}>
<div className="form-group">
<input type="text" placeholder="Name"
name="name" value={name}
onChange={e=>onChange(e)}
required />
</div>
<div className="form-group">
<input type="email"
placeholder="Email Address"
name="email" value={email}
onChange={e=>onChange(e)} />
<small className="form-text"
>This site uses Gravatar so if you want a profile image, use a
Gravatar email</small
>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
value={password}
onChange={e=>onChange(e)}
minLength="6"
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Confirm Password"
name="password2"
value={password2}
onChange={e=>onChange(e)}
minLength="6"
/>
</div>
<input type="submit" className="btn btn-primary" value="Register" />
</form>
<p className="my-1">
Already have an account? <Link to="/login">Sign In</Link>
</p>
</div>
)
}
export default connect(null,{setAlert,register}) (Register);
Server API code :
const express =require('express');
const User=require('../../models/User');
const gravatar=require('gravatar');
const {check, validationResult}=require('express-validator');
const bcrypt=require('bcryptjs');
const jwt=require('jsonwebtoken');
const router=express.Router();
const config=require('config');
// signin
router.post('/',[
check('name','name is required').not().isEmpty(),
check('email','Need valid email').isEmail(),
check('password','length should be greater than 6').isLength({min:6})
],async(req,res)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors:errors.array()});
}
const {name,email,password}=req.body;
try{
let user= await User.findOne({email});
if(user){
return res.status(400).json({errors:'user already exist !'})
}
const avatar =gravatar.url({email})
user= new User({
name,
email,
password,
avatar
})
const salt=await bcrypt.genSalt(10);
user.password=await bcrypt.hash(password,salt);
await user.save();
const payload={
user:{
id:user.id
}
}
jwt.sign(payload,config.get('jwtsecret'),(err,token)=>{
if(err){
throw err;
}
res.json({token});
})
}
catch(err){
return res.status(400).json({errors:errors.message})
}
});
module.exports=router;

Sendgrid in Vercel not sending email in production

I'm using SendGrid to send emails in my serverless Next.js project, deployed in Vercel, which works perfectly in development mode. But I'm having problems in production.
The error returned is:
contact-us-4c7332c1e7bfe2127d39.js:1 POST https://mywebsite.vercel.app/api/send 400
Yes, I enabled "Allow Less Secured Apps" in Google account and verify a Sender Identity in SendGrid.
Anybody experienced this kind of problem? How can I fix this?
This is the contact-us.js page
import Head from 'next/head'
import React, { useState } from 'react'
export default () => {
const [status, setStatus] = useState({
submitted: false,
submitting: false,
info: { error: false, msg: null }
})
const [inputs, setInputs] = useState({
name: '',
phone: '',
email: '',
message: ''
})
function SubmitButton(){
if (inputs.name && inputs.email && inputs.message) {
return <button type="submit" className="btn-submit" disabled={status.submitting}> {!status.submitting ? !status.submitted ? 'Submit' : 'Submitted' : 'Submitting...'} </button>
} else {
return <button type="submit" className="btn-submit" disabled>Submit</button>
};
};
const handleResponse = (status, msg) => {
if (status === 200) {
setStatus({
submitted: true,
submitting: false,
info: { error: false, msg: msg }
})
setInputs({
name: '',
phone: '',
email: '',
message: ''
})
} else {
setStatus({
info: { error: true, msg: msg }
})
}
}
const handleOnChange = e => {
e.persist()
setInputs(prev => ({
...prev,
[e.target.id]: e.target.value
}))
setStatus({
submitted: false,
submitting: false,
info: { error: false, msg: null }
})
}
const handleOnSubmit = async e => {
e.preventDefault()
setStatus(prevStatus => ({ ...prevStatus, submitting: true }))
const res = await fetch('/api/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(inputs)
})
const text = await res.text()
handleResponse(res.status, text)
}
return (
<div className="contact">
<main>
<div>
<h2>Get in touch!</h2>
<h3>How can we help you?</h3>
</div>
<form onSubmit={handleOnSubmit}>
<div className="form-group">
<input
id="name"
type="text"
name="name"
onChange={handleOnChange}
required
value={inputs.name}
className={inputs.name ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="name">Name</label>
</div>
<div className="form-group">
<input
id="email"
type="text"
name="email"
onChange={handleOnChange}
required
value={inputs.email}
className={inputs.email ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="email">Email</label>
</div>
<div className="form-group">
<input
id="phone"
type="tel"
name="phone"
onChange={handleOnChange}
required
value={inputs.phone}
className={inputs.phone ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="phone">Phone</label>
</div>
<div className="form-group">
<textarea
id="message"
onChange={handleOnChange}
required
value={inputs.message}
className={inputs.message ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="message">Message</label>
</div>
<SubmitButton />
{status.info.error && (
<div className="message-feedback error">
<p>Error: {status.info.msg}</p>
</div>
)}
{!status.info.error && status.info.msg && (
<div className="message-feedback success">
<p>Thanks for messaging us!</p>
<p>We'll get back to you soon.</p>
</div>
)}
</form>
</main>
</div>
)
}
And the /api/send.js
const sgMail = require('#sendgrid/mail')
export default async function(req, res) {
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const { phone, email, message } = req.body
const msg = {
to: 'myemail#outlook.com', // Change to your recipient
from: 'mysenderemail#gmail.com', // Change to your verified sender
subject: `New Message From - ${email}`,
text: message,
html: `
<p>Phone: ${phone}</p>
<p>Sent from: ${email}</p>
<div>${message}</div>
`
}
try {
await sgMail.send(msg)
res.status(200).send('Message sent successfully.')
} catch (error) {
console.log('ERROR', error)
res.status(400).send('Message not sent.')
}
}
Thank you.

Why are my POST and PUT requests from Node/Express not working in React/Redux? My GET and DELETE requests all work fine. All requests work in Postman

So, I have the issue that everything works in Postman and my GET and DELETE requests even work in the full-stack program (Node/Express, React/Redux/Hooks, Microsoft SQL Server), but my POST and PUT requests are not working. As you can see in the image below, I have 403 errors and those lines are from "console.log(data);", not my error handler/catcher, so it is a "good" request, but something is not authorizing. Console logs and service file to show that data is passing, but not being accepted can be viewed here.
I have tried many, many solutions and much research. As far as I understand, this COULD be an issue with CORS, but I'm really not sure. Also, in Redux DevTools, it does not show my "UPDATE_DEVICE" OR "CREATE_DEVICE" actions, so I know that they are not even being accepted.
Here is code from AddDevice:
import { useDispatch } from "react-redux";
import { createDevice } from "../actions/devices";
const AddDevice = () => {
const initialDeviceState = {
id: null,
title: "",
detail: "",
published: false
};
const [device, setDevice] = useState(initialDeviceState);
const [submitted, setSubmitted] = useState(false);
const dispatch = useDispatch();
const handleInputChange = event => {
const { name, value } = event.target;
setDevice({ ...device, [name]: value });
};
const saveDevice = () => {
const { title, detail } = device;
dispatch(createDevice(title, detail))
.then(data => {
setDevice({
id: data.id,
title: data.title,
detail: data.detail,
published: data.published
});
setSubmitted(true);
console.log(data);
})
.catch(e => {
console.log(e);
});
};
const newDevice = () => {
setDevice(initialDeviceState);
setSubmitted(false);
};
return (
<div className="submit-form">
{submitted ? (
<div>
<h4>You submitted successfully!</h4>
<button className="btn btn-success" onClick={newDevice}>
Add
</button>
</div>
) : (
<div>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
required
value={device.title}
onChange={handleInputChange}
name="title"
/>
</div>
<div className="form-group">
<label htmlFor="detail">Detail</label>
<input
type="text"
className="form-control"
id="detail"
required
value={device.detail}
onChange={handleInputChange}
name="detail"
/>
</div>
<button onClick={saveDevice} className="btn btn-success">
Add
</button>
</div>
)}
</div>
);
};
export default AddDevice;
And here is from my code for updating the device:
useEffect(() => {
getDevice(props.match.params.id);
}, [props.match.params.id]);
const handleInputChange = event => {
const { name, value } = event.target;
setCurrentDevice({ ...currentDevice, [name]: value });
};
const updateStatus = status => {
const data = {
id: currentDevice.id,
title: currentDevice.title,
detail: currentDevice.detail,
published: status
};
dispatch(updateDevice(currentDevice.id, data))
.then(response => {
console.log(response);
setCurrentDevice({ ...currentDevice, published: status });
setMessage("The status was updated successfully!");
})
.catch(e => {
console.log(e);
});
};
const updateContent = () => {
dispatch(updateDevice(currentDevice.id, currentDevice))
.then(response => {
console.log(response);
setMessage("The device was updated successfully!");
props.history.push("/devices");
})
.catch(e => {
console.log(e);
});
};
const removeDevice = () => {
dispatch(deleteDevice(currentDevice.id))
.then(() => {
props.history.push("/devices");
})
.catch(e => {
console.log(e);
});
};
return (
<div>
{currentDevice ? (
<div className="edit-form">
<h4>Device</h4>
<form>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
name="title"
value={currentDevice.title}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="detail">Detail</label>
<input
type="text"
className="form-control"
id="detail"
name="detail"
value={currentDevice.detail}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
{currentDevice.published ? "Published" : "Pending"}
</div>
</form>
{currentDevice.published ? (
<button
className="m-3 btn btn-sm btn-danger"
onClick={() => updateStatus(false)}
>
UnPublish
</button>
) : (
<button
className="m-3 btn btn-sm btn-danger"
onClick={() => updateStatus(true)}
>
Publish
</button>
)}
<button className="m-3 btn btn-sm btn-danger" onClick={removeDevice}>
Delete
</button>
<button
type="submit"
className="btn btn-success"
onClick={updateContent}
>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Please click on a device.</p>
</div>
)}
</div>
);
};
export default Device;
And finally, this is my server.js code from back-end:
var express = require('express');
var bodyParser = require('body-parser');
const cors = require("cors");
var app = express();
var corsOptions = {
origin: "http://localhost:8083"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
const db = require('./app/config/db.config');
const Role = db.role;
db.sequelize.sync();
// db.sequelize.sync({ force: true }).then(() => {
// console.log("Drop and re-sync db.");
// initial();
// });
// CODE ABOVE MAY BE NECESSARY FOR DATABASE TESTING, ESPECIALLY IF DATABASE MIGRATION OCCURS BECAUSE THE "initial" FUNCTION ESTABLISHES ROLES, WHICH IS CRUCIAL
require("./app/router/router.js")(app);
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
function initial(){
Role.create({
id: 1,
name: "USER"
});
Role.create({
id: 2,
name: "ADMIN"
});
Role.create({
id: 3,
name: "PM"
});
}
Sending request is in a wrong format.
axios.post (url, data, {...headers here})

How to send User to Next Page After form validation in react?

This in My SignUp Component, Im trying To send User to Signin Component If Username And Password Is correct.
this is Signup Code Below,
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Axios from 'axios';
const initianValue = {
username: '',
password: '',
nameError: '',
passError: '',
dataError: '',
};
class SignUp extends Component {
constructor(props) {
super(props);
this.state = initianValue;
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
validForm() {
let nameError = '';
let passError = '';
let dataError = '';
const user = {
username: this.state.username,
password: this.state.password,
};
if (!this.state.username) {
nameError = 'Enter Name';
}
if (user.username !== '' && user.password !== '') {
Axios.post('http://localhost:9000/checkUser', user)
.then((res) => this.setState({ dataError: res.data }))
.catch((err) => console.log(err));
}
if (!this.state.password) {
passError = 'Enter Password';
}
if (nameError || passError || dataError) {
this.setState({
nameError,
passError,
dataError,
});
return false;
}
return true;
}
handleSubmit = (e) => {
e.preventDefault();
const isvalid = this.validForm();
if (isvalid) {
this.setState(initianValue, () => this.props.history.push('/SignIn'));
}
};
render() {
return (
<div className='Main'>
<span className='create'>Create Account</span>
<div className='SignUp'>
<form onSubmit={this.handleSubmit}>
<div className='form-group'>
<label>Username</label>
<input
type='text'
name='username'
value={this.state.username}
className='form-control'
onChange={this.handleInputChange}
/>
<div className='error'>
{this.state.nameError}
{this.state.dataError}
</div>
<br />
<label>Password</label>
<input
type='password'
name='password'
value={this.state.password}
className='form-control'
onChange={this.handleInputChange}
/>
<div className='error'>{this.state.passError}</div>
<br />
<button type='submit' className='btn btn-primary'>
Sign Up
</button>
</div>
</form>
</div>
<div className='signinForm'>
<label>
Already Have Account <Link to='/Signin'> Sign In </Link>
</label>
</div>
</div>
);
}
}
export default SignUp;
Its Works Perfect If I Put Right username and password but in wrong username / password its also send me to Signin Page and Shows warning in console like this
index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in SignUp (created by Context.Consumer)
i wrap Both Component SignUp And Signin In Router,
this is my server.js file to send data if username and password is correct in database
app.post('/checkUser', function (req, res) {
const name = req.body.username;
const pass = req.body.password;
conn.query(
`SELECT * FROM users WHERE username = (?) AND password = (?) `,
[name, pass],
(err, rows) => {
if (err) throw err;
if (!rows.length) {
res.send('Wrong Data');
}
}
);
});
Your validForm makes an async call. By the time the async call is finished the validForm function as well as handleSubmit function execution is already completed. Then the then block is executed where you are setting state and therefore the error.
Solution: Make validForm an async function and await for your async call. Also make handleSubmit function an async and await for validForm.
Working demo
Code snippet
class SignUp extends Component {
constructor(props) {
super(props);
this.state = initianValue;
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
async validForm() {
let nameError = "";
let passError = "";
let dataError = "";
const user = {
username: this.state.username,
password: this.state.password
};
if (!this.state.username) {
nameError = "Enter Name";
}
if (user.username !== "" && user.password !== "") {
await Axios.get("https://jsonplaceholder.typicode.com/todos/1", user) //fake api
.then(res => {
dataError = "user already exists"; //provide dynamic error..
//this.setState({ dataError: res.data }); // not required
})
.catch(err => console.log("err", err));
}
if (!this.state.password) {
passError = "Enter Password";
}
if (nameError || passError || dataError) {
this.setState({
nameError,
passError,
dataError
});
return false;
}
return true;
}
handleSubmit = async e => {
e.preventDefault();
const isvalid = await this.validForm();
if (isvalid) {
this.setState(initianValue, () => this.props.history.push("/SignIn"));
}
};
render() {
return (
<div className="Main">
<span className="create">Create Account</span>
<div className="SignUp">
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
name="username"
value={this.state.username}
className="form-control"
onChange={this.handleInputChange}
/>
<div className="error">
{this.state.nameError}
{this.state.dataError}
</div>
<br />
<label>Password</label>
<input
type="password"
name="password"
value={this.state.password}
className="form-control"
onChange={this.handleInputChange}
/>
<div className="error">{this.state.passError}</div>
<br />
<button type="submit" className="btn btn-primary">
Sign Up
</button>
</div>
</form>
</div>
<div className="signinForm">
<label>
Already Have Account <Link to="/Signin"> Sign In </Link>
</label>
</div>
</div>
);
}
}
The issue could be on the handling of the response of the fetch. This is just a quick guess but try to not set the state of dataError and just modify the value of your variable dataError that you declared in this local function instead of the class variable. Does that make sense? when you check in your "if (nameError || passError || dataError)" you are checking for the local variable of your function and not the class which I think is fine but you aren't changing the variable if the response is an error.
Second if you change the setState and then check the state.dataError you might not get the updated value refresh yet in the function.
Let me know if that makes sense and if it works.

Cannot POST /Admin

I was connecting react with my api in node js, but when connecting to the login the only thing that appears is "Cannot POST / Admin"
I have used the Postman and it seems that the back part works because the token returns, but I think there is some problem in the connection between the two.
I am working on react, nodejs, redux and mongodb
interface IProps {}
interface IPropsGlobal {
setToken: (t: string) => void;
setName: (u: string) => void;
}
const Login: React.FC<IProps & IPropsGlobal> = props => {
const [username, setUsername] = React.useState("");
const [password, setPassword] = React.useState("");
const [error, setError] = React.useState("");
const updateUsername = (event: React.ChangeEvent<HTMLInputElement>) => {
setUsername(event.target.value);
setError("");
};
const updatePassword = (event: React.ChangeEvent<HTMLInputElement>) => {
setPassword(event.target.value);
setError("");
};
const signIn = () => {
fetch("http://localhost:3006/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
password: password
})
})
.then(response => {
if (response.ok) {
response
.text()
.then(token => {
console.log(token);
props.setToken(token);
props.setName(username);
});
} else {
setError("Usuario o Contraseña incorrectos");
}
})
.catch(err => {
setError("Usuario o Contraseña incorrectos.");
});
};
return (
<div>
<div className="section"></div>
<h5 className="indigo-text">Please, login into your account</h5>
<div className="section"></div>
<div className="container">
<div className="z-depth-1 grey lighten-4 row er" >
<form className="col s12" method="post">
<div className='row'>
<div className='col s12'>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' name='email' id='email' value={username}
onChange={updateUsername}/>
<label >Enter your email</label>
</div>
</div>
<div className='row'>
<div className='input-field col s12'>
<input className='validate' type='password' name='password' id='password' value={password}
onChange={updatePassword} />
<label >Enter your password</label>
</div>
<label >
<a className='pink-text' href='#!'><b>Forgot Password?</b></a>
</label>
</div>
<br />
<div className='row'>
<button type='submit' name='btn_login' className='col s12 btn btn-large waves-effect indigo'
onClick={signIn}>Login</button>
</div>
</form>
</div>
</div>
Create account
</div>
);
};
const mapDispatchToProps = {
setToken: actions.setToken,
setName: actions.setName
};
export default connect(
null,
mapDispatchToProps
)(Login);
Postman returns the token
The api console shows me:
POST /api/auth - - ms - -
Connected successfully to server
In the Web page
Failed to load resource: the server responded with a status of 404 (Not Found)
I have used this code or a similar one before in other projects but I do not understand what happened to me this time
const md5 = require('md5');
// Connection URL
const mongoUrl = 'mongodb://localhost:27017';
// Database Name
const mongoDBName = 'ArdalesTur';
/* GET users listing. */
router.get('/', (req, res) => {
res.send('respond with a resource');
});
const secret = 'mysecret';
// para interactuar con la base de datos
router.post('/auth', (req, res) => {
mongo.MongoClient.connect(mongoUrl, (err, client) => {
assert.equal(null, err);
console.log('Connected successfully to server');
const db = client.db(mongoDBName);
const query = db.collection('Admin').find({
username: req.body.username,
password: md5(req.body.password),
});
query.toArray().then((documents) => {
if (documents.length > 0) {
const token = jwt.sign(
{
_id: documents[0]._id,
username: documents[0].username
},
secret,
// {
// expiresIn: 86400
// }
);
res.send(token);
} else {
res.status(400).send('Invalid credentials');
}
});
client.close();
});
});
here you have the api

Resources