GET Ajax returns html code in response instead of json object

主宰稳场 提交于 2019-12-10 16:20:22

问题


I have an ajax get request as below. I am making a GET request to server.js in openshift using nodejs express. However, i get html contents in the response method instead of json object. Both the requests are for the same domain.The node modules that I am using are moongojs,mongodb and bson.

$.ajax({
           type: "GET",
           url: "http://abc-favspot.rhcloud.com",
           contentType: "application/json",
           data: JSON.stringify(currLocation),
           dataType: "text",
           success: function(response){
           callback(response);
               },
            error: function( error ){
            console.log( "ERROR:", error );

                }
            });

My server.js file has the following code

self.routes['getData'] = function(req, res){
        console.log("gat method");            

    self.db.collection('location').find().toArray(function(err, names) {
       res.header("Content-Type:","application/json");
        console.log("success get");            
        res.send(names);
    });
  };

回答1:


res.send(names) is not JSON, You have to stringify the data using JSON.stringify.

Try testing before the DB call to check if it works.

res.send( JSON.stringify( {testData:'test'} ) )

Edit

As discussed in the comments, please check to ensure that your request is routed to the correct route that you declared.

Does console.log("gat method"); output anything to the terminal window?




回答2:


in your $.ajax method call change this

dataType: "text",

to

dataType: "json",

refer to the documentation for the further details

https://api.jquery.com/jQuery.ajax/

and please check if the data you receive is a valid json, check it with http://jsonlint.com/




回答3:


You can use res.json to send JSON response instead of res.send

res.json(obj)

This method also set Content-Type as application/json



来源:https://stackoverflow.com/questions/23208449/get-ajax-returns-html-code-in-response-instead-of-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!