简体   繁体   中英

Sending a JSON with request in Node.js

I'm using request module to send data to a server.

I wrote this:

... 
      var httpOptions = {
        host: localStorage.host,
        path: localStorage.path,
        port: localStorage.port,
        method: 'POST',
        body: $scope.jsonToSend,
        json: true,
        headers: {
          'Content-Type': 'application/json',
        }
      };
 ...

try {
        var request = http.request(httpOptions, httpCallback);
        request.on('error', function(err) {
          $scope.hasHttpError = true;
          $scope.httpErrorMessage = 'NETWORK error '+err;
          $scope.sending = false;
          $scope.$apply();
        });
        request.write($scope.jsonToSend);
        request.end();

      } catch (e) {

        $scope.hasHttpError = true;
        $scope.httpErrorMessage = 'NETWORK error '+e.toString();
        $scope.sending = false;
        $scope.$apply();
      } finally {

      }

But I'm getting this error:

Error: NETWORK error TypeError: First argument must be a string or Buffer

Naturally it's referred to request.write function. My question is, how can I can send JSON to a server?

使用request.write(JSON.stringify($scope.jsonToSend))然后在获取响应时将其解析为json对象

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM