RailBatyrshin
Programmer
Hi all, can someone explain to me, how does communicate frontend and backend? I have a project, that dividing into frontend and backend folders. And I can't understand how can I send the data from the registration form to the server-side using Fetch API. I want to create a SPA.
Thank you in advance, and sorry for my English.
Best regards!
P.s: The structure of my project in the attached files.
This is the code on the frontend:
And this is the code on the backend (server.js):
Thank you in advance, and sorry for my English.
Best regards!
P.s: The structure of my project in the attached files.
This is the code on the frontend:
JavaScript:
const formData = {
name: name.value,
age: age.value.split('-').join('.'),
email: email.value,
password: pass.value,
};
const checkResponseStatus = function(res) {
if (res.ok) {
return res;
} else {
throw new Error(`The HTTP status of the response: ${ res.status } (${ res.statusText })`);
}
};
const url = '/register';
const request = new Request(url, {
method: 'POST',
body: JSON.stringify(formData),
headers: { 'Content-Type': 'application/json' }
});
fetch(request)
.then(checkResponseStatus)
.then(response => response.json())
.catch(err => console.log(err));
name.value = '';
age.value = '';
email.value = '';
pass.value = '';
repeatPass.value = '';
for (let key of Object.keys(formData)) {
delete formData[key];
}
JavaScript:
const express = require('express');
const bodyParser = require('body-parser');
const router = express.Router();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res) => {
const post_data = req.body;
console.log(post_data);
});
router.get('/', (req, res) => {
res.sendFile('../frontend/index.html');
});
router.post('/register', (req, res) => {
const user_name = req.body.name;
const password = req.body.password;
console.log(`User name: ${ user_name }, password: ${ password }`);
res.end('YES');
});
app.listen(3000, () => {
console.log(`Started on PORT 3000`);
});