I can't connect to my Express server. I'm trying to use Axios to connect from my front end but it never reaches the endpoint. Also when I attempt to connect directly from the browser it just spins. When I start the server, I do see the console log message from the listen function, so it appears to be running. But the Axios.post never gets tot he /login route.
Here is my index.js on the Server
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
app.use(cors);
app.use(express.json());
const db = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
databaseName: 'ncaa'
});
app.post("/login", (req, res) => {
const userName = req.body.userName;
const password = req.body.password;
db.query("SELECT * from user where username = ? and password = ?", [userName, password], (err, result) => {
if(err){
res.send({err: err});
}
if (result){
res.send(result);
}
else {
res.send({message: "Username or password is incorrect"});
}
});
});
app.listen(3001, () => {
console.log('App running on 3001');
});
Here is my app.js on the client
import React from 'react';
import { useState } from 'react';
import Axios from 'axios';
import './App.css';
function App() {
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const authenticateLogin = () => {
Axios.post("http://localhost:3001/login", {
userName: userName,
password: password
}).then((response) => {
console.log(response);
});
}
return (
<div className="App">
<div className="login">
<h1>Login</h1>
<label>Username:</label>
<input type="text" onChange={(event) => { setUserName(event.target.value) }}/>
<label>Password:</label>
<input type="password" onChange={(event) => { setPassword(event.target.value) }}/>
<button onClick = {authenticateLogin}>Login</button>
</div>
</div>
);
}
export default App;
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors()); // cors is a function, you have to call that function
app.use(express.json());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.