@alexander_kuznecov
frontend developer

Почему не передаются данные из формы jsx в базу данных mysql???

// ./frontend/Login.jsx
import React, { useState } from 'react';
import axios from 'axios';

function Login() {
	const [name, setName] = useState('');
	const [email, setEmail] = useState('');
	const [password, setPassword] = useState('');

	const handleSubmit = (event) => {
		event.preventDefault();
		axios.post('http://localhost:8081/login', {name, email, password})
		.then(res => console.log(res))
		.catch(err => console.error(err));
	}
	return (
		<div>
			<form onSubmit={handleSubmit}>
				<div>
					<label htmlFor='name'>Name</label>
					<input required onChange={e => setName(e.target.value)} type='text' placeholder='Enter name' />
				</div>
				<div>
					<label htmlFor='email'>Email</label>
					<input required onChange={e => setEmail(e.target.value)} type='text' placeholder='Enter name' />
				</div>
				<div>
					<label htmlFor='password'>Password</label>
					<input required onChange={e => setPassword(e.target.value)} type='password' placeholder='Enter name' />
				</div>
				<button type='submit'>Login</button>
			</form>
		</div>
	);
}

export default Login;


// ./backend/server.js
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cors());
const db = mysql.createConnection({
	host: 'localhost',
	user: 'root',
	password: 'sho0O-a+z1#Lpd(./y%f',
	database: 'login',
});

app.post('/login', (req, res) => {
	const sql = `INSERT INTO users (user_id, name, email, password_hash) VALUES (444435346,'Hello','Alex@gmail.com', qwerty12345);`;
	const values = [req.body.name, req.body.email, req.body.password];
	db.query(sql, [values], (error, data) => {
		if (error) {
			return res.json('Error!');
		}
		if (data.length > 0) {
			return res.json('Login success!');
		} else {
			return res.json('No record!');
		}
	});
});

app.listen(8081, () => {
	console.log('listening on 8081 port');
});
  • Вопрос задан
  • 95 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы