javascript - 带有 Node 的 Http 请求?

标签 javascript http node.js httpclient

如何使用 node.js 发出与此代码等效的 Http 请求:

curl -X PUT http://localhost:3000/users/1

最佳答案

对于其他在谷歌上搜索此问题的人,接受的答案不再正确并且已被弃用。

正确的方法(在撰写本文时)是使用 http.request 方法,如下所述:nodejitsu example

代码示例(来自上面的文章,已修改以回答问题):

var http = require('http');

var options = {
  host: 'localhost',
  path: '/users/1',
  port: 3000,
  method: 'PUT'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();

关于javascript - 带有 Node 的 Http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4294939/

相关文章:

node.js - Express 中 Mongoose 验证失败后如何向客户端返回错误消息

node.js - 均衡 : TypeError: Class constructor Modal cannot be invoked without 'new' (typescript)

javascript - 如何将 PHP 结果创建的字符串提供给我的 javascript

javascript - 按 'ctrl' 键时,jQuery 选项卡插件未在新浏览器选项卡中打开

C++ Windows HTTP

java - android 中是否可以使用 java 套接字程序通过 http 传输文件?

javascript - React.js onclick事件: Cannot read property 'props' of undefined

javascript - 如何禁用 CKEditor 上下文菜单?

javascript - AngularJS - $http.get 请求被取消

javascript - 删除父文档时 Mongoose 删除子文档引用