javascript - Why shouldn't the server respond with a JSON Array?

后端 未结 2 620
醉话见心
醉话见心 2021-01-28 15:29

According to this Angular 2 guide:

Don\'t expect the decoded JSON to be the heroes array directly. This server always wraps JSON results in an object wit

2条回答
  •  独厮守ぢ
    2021-01-28 16:16

    To avoid JSON Hijacking:

    The fact that this is a JSON array is important. It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file.

    For example, if you had a JavaScript file that contained the following JSON: {“Id”:1, “Balance”:3.14} And you had a script tag that referenced that file:

    You would get a JavaScript error in your HTML page. However, through an unfortunate coincidence, if you have a script tag that references a file only containing a JSON array, that would be considered valid JavaScript and the array gets executed.

    So allowing JSON to be returned as anything but an object would make it possible to return a JSON array that contained code that could be run on the client level (in a context where the client isn't expecting it to be runnable, could be malicious, etc). Only returning JSON objects prevents this from happening.

提交回复
热议问题