Here is the server
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors')
const app = express();
const port = 3000;
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '******',
database: 'book_store'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
});
app.use(cors())
app.options('/users', ( res ) => {
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.sendStatus(200);
});
app.use(bodyParser.json());
app.get('/books', ( res ) => {//get books db
connection.query('SELECT * FROM books', (err, results) => {
if (err) throw err;
const result = res.json(results)
console.log(result)
});
});
app.get('/users', ( res ) => {//get users db
connection.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
const result = res.json(results)
console.log(result)
});
});
app.options('/users', cors())
app.post('/users', (req, res) => {
const { username, email, password, address, role } = req.body;
console.log('request body', req.body)
connection.query('INSERT INTO users (username, email, password, address, role) VALUES (?, ?, ?, ?, ?)',
[username, email, password, address, role],
(err, result) => {
if (err) {
console.error("Error inserting user:", err);
res.status(500).json({ error: 'Error inserting user' });
} else {
console.log("User inserted successfully");
res.status(200).json({ success: true });
}
})
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Here is the front end request
function addUser(username, email, password, address, role) {
// Define the data to be sent in the request body
const userData = {
username: username,
email: email,
password: password,
address: address,
role: role
};
// Make a POST request to the server endpoint
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*'
},
body: JSON.stringify(userData) // Convert the data to JSON format
})
.then(response => {
if (!response.ok) {
throw new Error('Failed to add user');
}
return response.json(); // Parse the response JSON
})
.then(data => {
console.log('User added successfully:', data);
// Handle success if needed
})
.catch(error => {
console.error('Error adding user:', error.message);
// Handle error if needed
});
}
addUser(username, email, password, address, role)
This are the headers i get
Request URL:
http://localhost:5500/users
Request Method:
POST
Status Code:
405 Method Not Allowed
Remote Address:
127.0.0.1:5500
Referrer Policy:
strict-origin-when-cross-origin
Access-Control-Allow-Credentials:
true
Access-Control-Allow-Origin:
http://localhost:5500
Allow:
GET, HEAD, OPTIONS
Connection:
keep-alive
Content-Length:
0
Date:
Wed, 24 Apr 2024 23:35:01 GMT
Keep-Alive:
timeout=5
Vary:
Origin
Accept:
/
Accept-Encoding:
gzip, deflate, br, zstd
Accept-Language:
es-US,es;q=0.9,es-419;q=0.8,en;q=0.7
Connection:
keep-alive
Content-Length:
91
Content-Type:
application/json
Cookie:
_ga=GA1.1.2077515680.1676588089; _ga_2JPB0HJG8R=GS1.1.1701138391.13.0.1701138391.0.0.0
Host:
localhost:5500
Origin:
http://localhost:5500
Referer:
http://localhost:5500/front/
Sec-Fetch-Dest:
empty
Sec-Fetch-Mode:
cors
Sec-Fetch-Site:
same-origin
User-Agent:
Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1
I keep getting error 405(Method not Allowed). Any advice?
Tried modificating cors headers, but still didnt work. Using postman to POST to server seems to work fine.