also iam not able to access controll allow – body
server js
working on local data.json
working origin is diffrent port thas CORS used
const http = require('http');
const url = require('url');
const fs = require('fs');
http.createServer((req, res)=>{
var q = url.parse(req.url, true);
if (req.method == "OPTIONS"){ //Preflight
console.log("hy");
res.writeHead(204, {
"Access-Control-Allow-Headers" : 'content-type, body',
"Access-Control-Allow-Origin" : 'http://127.0.0.1:5500'
});
res.end();
}
else if(req.method == "GET"){
if(q.pathname === "/xyz"){
fs.readFile('data.json', (err, data)=>{
res.writeHead(200, {
"Content-type": 'application/json',
"Access-Control-Allow-Origin" : 'http://127.0.0.1:5500'
})
res.write(data);
res.end()
});
}
}
else if(req.method == "POST"){
res.writeHead(200, {
"Content-type": 'application/json',
"Access-Control-Allow-Origin" : 'http://127.0.0.1:5500'
});
const d = req.headers.body;
//first tell me it's wrong or write , i dont know so much about web server
//adding value in json formate but if json is emapty its not puting and[] also not puting any ,
// my meaning of this is not following index
//.push() method is not allowed
fs.appendFile('data.json',d, (err) => console.log(err))
res.end()
}
}).listen(8080, () => console.log(`Server started on port 8000`));
request post js
fetch ('http://localhost:8080/xyz', {
method:"POST",
headers:{
'Content-type': 'application/json',
"body":JSON.stringify({
Name:"Hitesh",
surName:"Chaudhary",
age:23,
userid:1,
learning:["html","css","java_script", "MERN Stack"],
batch:"21MAY03"
})
},
})
.then((getresponse)=>getresponse.json())
.then((data)=>console.log(data))
.catch((err)=>console.log("this error" +err));