如何发送带有提取的数组? (JavaScript)

时间:2019-05-31 13:23:40

标签: javascript node.js express

我正在尝试使用看起来像这样的获取来发送数组:

this.Data = [{"StateAbbr": "AZ", "StateName":"Arizona"},
               {"StateAbbr": "FL", "StateName":"Florida"}];


            this.chartOptions = function () {
                return {
                    chart: { renderTo: 'geographySection', borderWidth: 0 
                     },                        
                    mapNavigation: { enabled: false },
                    series: this.series(),
                    credits: { enabled: false }                      
                };
            };

            this.series = function () {
                return [{
                    animation: { duration: 1000 },
                    showInLegend: false,
                    data: this.Data,
                    mapData: Highcharts.maps['countries/us/us-all'],
                    joinBy: ['postal-code', 'StateAbbr'],
                    dataLabels: { enabled: true, format: '{point.StateAbbr}' },
                    tooltip: {  headerFormat: '', pointFormat: '{point.StateName}' }

                }];
            };

            new Highcharts.Map(this.chartOptions());

这是我正在尝试的:

{"cards":[[189,2],[211,2],[238,2],[778,2],[985,2],[1008,2],[1073,2],[1171,2],[48886,2],[49161,2],[49164,2],[49184,1],[49356,2],[50372,2],[51722,1],[52422,2]],"heroes":[1066],"format":2}

我遇到了一个错误:

 getCardsForDeck = deck => {
    var stringifiedDeck = JSON.stringify(deck);
    console.log("stringifiedDeck:" + stringifiedDeck);
    fetch(`http://localhost:3001/api/getCardsForDeck`, {
      method: "PUT",
      body: stringifiedDeck
    })
      .then(cards => cards.json())
      .then(res => this.setState({ cards: res.cards }));
  };

如果不使用JSON.stringify()来发送此数据,还是必须编辑数据以删除括号?

在检查网络标签中的api后,我会看到以下信息:

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0

1 个答案:

答案 0 :(得分:4)

您似乎期望http://localhost:3001/api/getCardsForDeck向其发送JSON 后向其发送JSON 返回。很有可能它是用HTML而不是JSON响应的。

该代码中还有其他两个错误:

  1. 您需要说出要发送的内容,因为它不是默认的URI编码数据:

    fetch(`http://localhost:3001/api/getCardsForDeck`, {
      method: "PUT",
      body: stringifiedDeck,
      headers: {                              // ***
        "Content-Type": "application/json"    // ***
      }                                       // ***
    })
    
  2. 您需要检查响应的状态。 (每个人都会错过它。)最简单的方法是检查响应上的ok标志:

    fetch(`http://localhost:3001/api/getCardsForDeck`, {
      method: "PUT",
      body: stringifiedDeck,
      headers: {
        "Content-Type": "application/json"
      }
    })
    .then(response => {
      if (!response.ok) {                                  // ***
        throw new Error("HTTP error " + response.status);  // ***
      }                                                    // ***
      // ...use `response.json`, `response.text`, etc. here
    })
    .catch(error => {
      // ...handle/report error
    });