I know my way in HTML, CSS, and JS; I have mongoDB and I want to build a full stack application without any additional library, plain vanilla JS, this app will run offline on a stand alone computer with no internet access, I want to be able to connect to the back end, send, request, delete and modify data if necessary. And as context this will be an app that will allow an admin person to keep track of students, classes, projects, completion, events, notifications and more. But I have an error accessing XMLHttpRequest between my localhost server and my localhost client, and obviously I’m not able to POST new data in my server side.
//App.js
const serverURL = 'https://localhost:3031';
function sendData(data) {
const xhr = new XMLHttpRequest();
xhr.open('POST', serverURL, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
document.getElementById('response').textContent = 'Data saved successfully';
} else {
console.error('Error: ' + xhr.status);
document.getElementById('response').textContent = 'Error sending data';
}
};
xhr.onerror = function() {
console.error('Network error');
document.getElementById('response').textContent = 'Network error';
};
xhr.send(JSON.stringify(data));
}
//Server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3031;
mongoose.connect('mongodb://localhost:27017/testingDB', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error(err));
app.use(express.json());
app.post('/data', (req, res) => {
const data = req.body;
console.log(data);
const newData = new YourDataModel(data);
newData.save()
.then(savedData => {
res.json({ message: 'Data saved successfully', data: savedData });
})
.catch(err => {
res.status(500).json({ error: 'Error saving data', message: err.message });
});
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
// I expected to be able to post my data in my newly created schema(omitted code)`