I am new to NodeJS and can't connect to the server http://localhost:6000/
server.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(express.urlencoded({extended: false}));
app.use(express.json);
app.use(cors());
app.use(express.static('website'));
const port = 6000;
const server = app.listen(port, listening);
function listening(){
console.log("localhost port: " port);
}
app.post('/postdata', (request, response) =>{
console.log("POST request received!");
});
app.get("/getdata", (request, response) =>{
})
app.js
const postData = async ( url = '', data = {})=>{
// console.log(data);
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
try {
const newData = await response.json();
console.log(newData);
return newData;
}catch(error) {
console.log("error", error);
}
}
postData('/postdata', {Works:456456});
[my code with the terminal output][1] [1]: https://i.stack.imgur.com/bJJUv.png
[browser - can't connect][2] [2]: https://i.stack.imgur.com/K19NS.png
What am i doing wrong?
CodePudding user response:
The issue seemed to be with missing brackets:
app.use(express.json());
CodePudding user response:
You are trying to send request to the server without base url. replace it in this way:
const postData = async ( url = '', data = {})=>{
// console.log(data);
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
try {
const newData = await response.json();
console.log(newData);
return newData;
}catch(error) {
console.log("error", error);
}
}
postData('http://localhost:6000/postdata', {Works:456456});
