in node.js express, how to tell the HTTP request is application/json or html on the content negoition in jquery -
i want node.js server send different content based on request's content type, server code
if(req.accepts('text/html')){ console.log("accepts('text/html')"); locals.page = 'posts'; res.render('question.ejs', locals.questions); } else if(req.accepts('application/json')){ console.log("'application/json'"); res.json(200,locals.questions); }
there similar post android client in node.js express, how tell http request application/json or html on content negoition
this jquery code
$.ajax({ type: "get", url: "/course/abc/questions", contenttype:"application/json; charset=utf-8", datatype:"json", success: function(data){ console.log(data.length,data); } });
for reason, set content type on appication/json, node.js server side still accepts html rather json.
a little strange
the headers different on request (jquery) vs response (express). on request/browser/jquery/ajax side, when making request, set accept header, meaning "i 1 of these formats". there no content-type
header because request has no body, header not applicable.
on server side, set content-type
, meaning "this response body of following format". semantics of accept can list of alternative formats, whereas content-type single value.
here's snippet copied this answer
$.ajax({ headers: { accept : "application/json; charset=utf-8" }, success : function(response) { ... } })
Comments
Post a Comment