I’m working on a game and want to save user stats on the server. By navigating to a URL with their userName I should be able to view their game-play stats. The data is stored in JSON format.
I’ve included my server-side and parts of client-side index.js files.
Server-Side index.js:
app.use(cors());
app.use(express.json());
const userName = document.getElementById('userName').innerHTML;;
app.post(`/data/${userName}`, (req, res) => {
try {
const data = dateien;
console.log('Received data:', data);
// Process the data as needed
res.status(200).json({ message: 'Data received successfully', data: data });
} catch (error) {
console.error('Error processing data:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
});
app.listen(3001, () => {});
Client-Side index.js:
function sendDataToServer(data) {
var userName = document.getElementById('userName').innerHTML;
fetch(`http://localhost:3000/data/${userName}`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error('Nope -- Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Client-Side package.json snippet:
"name": "client",
"version": "0.1.0",
"private": false,
"proxy": "http://localhost:3001",
"type": "module",
I suspect it has something to do with the route template ->
`http://localhost:3000/data/${userName}`
Because when I modify this to
`http://localhost:3000/data/George`
or any other exact userName, the data is received successfully. Can someone contribute and help clarify this issue?
Thanks!
nadela Ma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2