JavaScript&Node.js-控制器功能中的JSON字符串不正确

时间:2019-01-09 11:21:12

标签: javascript arrays node.js json

JavaScript和Node.js-控制器函数中的json字符串不正确

我正在通过ajax将JSON发送到Node.js中的路由。但是当我在node.js函数中获取req.body时,JSON看起来不正确。我想念什么?

JavaScript:

public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int LAYOUT_ONE= 0;
    private static final int LAYOUT_TWO= 1;

    @Override
    public int getItemViewType(int position)
    {
        if(position==0)
           return LAYOUT_ONE;
        else
           return LAYOUT_TWO;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view =null;
        RecyclerView.ViewHolder viewHolder = null;

        if(viewType==LAYOUT_ONE)
        {
           view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
           viewHolder = new ViewHolderOne(view);
        }
        else
        {
           view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
           viewHolder= new ViewHolderTwo(view);
        }

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

       if(holder.getItemViewType()== LAYOUT_ONE)
       {
           // Typecast Viewholder 
           // Set Viewholder properties 
           // Add any click listener if any 
       }
       else {

           ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
           vaultItemHolder.name.setText(displayText);
           vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   .......
               }
           });

       }

   }

   /****************  VIEW HOLDER 1 ******************//

   public class ViewHolderOne extends RecyclerView.ViewHolder {

       public TextView name;

       public ViewHolderOne(View itemView) {
       super(itemView);
       name = (TextView)itemView.findViewById(R.id.displayName);
       }
   }


  //****************  VIEW HOLDER 2 ******************//

  public class ViewHolderTwo extends RecyclerView.ViewHolder{

       public ViewHolderTwo(View itemView) {
       super(itemView);

           ..... Do something
       }
  }
}

控制台结果:

var getID = $('.input-id').val();
var getName = $('.input-name').val();

var books = $('.select-books').val();

var books = books.map(function(book) {
            return {id: book};
        });

var dataaddID = {};
dataaddID['add'] = { id : getID, name : getName, books };

var jsonaddID = JSON.stringify(dataaddID);

console.log(jsonaddID);

$.ajax({
    url:'/books/add',
    type:'POST',
    headers: {'X-CSRF-Token': csrfKey},
    dataType: 'json',
    data: jsonaddID,
    success:function(data){

        console.log(data);

    }

});

Node.js路由/功能

{"add":{"id":"T1088","name":"Zynula","books":[{"id":"1"},{"id":"2"}]}}

奇怪的结果:

postBooks: async (req, res, next) => {

    console.log(req.body);
    var getBody = JSON.stringify(req.body);
    console.log(getBody);

}

预期结果:

{ '{"add":{"id":"T1088","name":"Zynula","books":': { '{"id":"1"},{"id":"2"}': '' } }

{"{\"add\":{\"id\":\"T1088\",\"name\":\"Zynula\",\"books\":":{"{\"id\":\"1\"},{\"id\":\"2\"}":""}}

3 个答案:

答案 0 :(得分:1)

在发送数据之前,请尝试不使用JSON.stringify()。我相信Ajax会为您序列化它。

答案 1 :(得分:1)

我研究了一下快速解析。没有检查所有详细信息,原因是,如果您将数据作为字符串传递:

{"add":{"id":"T1088","name":"Zynula","books":[{"id":"1"},{"id":"2"}]}}

然后缺少应将内容解释为JSON的标头,并且解析器解释参数是否以key[subKey]=value形式传入名称/值对,因此解析器将其拆分为以下形式:

{"add":{"id":"T1088","name":"Zynula","books":
  [
     {"id":"1"},{"id":"2"}
  ]
}}

因此{"add":{"id":"T1088","name":"Zynula","books":是第一个键的ID,而{"id":"1"},{"id":"2"}子键和最后的}}则被忽略,因此值为''

因此,要么在不使用stringify的情况下将其作为对象传递(例如Dev Yego),然后jQuery就会为您序列化数据并添加正确的标头,告诉服务器为application/x-www-form-urlencoded(格式为jQuery,如果格式化为)。

如果将数据发送到的API需要JSON,则需要添加自己的正确标头:

data: JSON.stringify(yourData),
contentType: 'application/json; charset=utf-8',

答案 2 :(得分:0)

而不是尝试

var sendBody = JSON.stringify(req.body);

尝试

var sendBody = JSON.parse(req.body);

您会得到答案