I'm not sure what i'm doing wrong here, I'm trying to set the content-type header when my server receives a post request. It's always going to be receiving an object, just with different data each time, so when it gets to the server, i need it to be an object.
http.createServer(function(request,response) {
response.setHeader('Content-Type', 'application/json');
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With")
var purl = "/api/forums/users/"
if(request.url == purl && request.method == "POST"){
response.setHeader('Content-Type', 'application/json');
console.log("Request Recieved!")
var bufdat = []
request.on('data',function(chunk){
bufdat.push(chunk)
var data = Buffer.concat(bufdat).toString()
console.log(data)
})
}
}).listen(6157)
Everything about this works, it receives the object from the client (the client in this case, is a chrome extension) And its sending the following post request to the server:
$.ajax({
url:'http://localhost:6157/api/forums/users/',
type:'POST',
data:{
name:"testname"
}
})
This does get to the server, however not in JSON format. On line 13 where I have console.log(data), it just prints out name=testname
, when it should be coming out as a JSON: {name:testname}
. I'm not sure where i'm going wrong, or why the it wont set the headers so every time i receive this post request, my object is in JSON format. I've looked at almost any post i've seen, and they've all just talked about using response.setHeader('Content-Type', 'application/json');
as you can see in my code, i've just taken shots in the dark by adding it on line 2, and 7, hoping to achieve my goal, however that has not worked.