将数据从swift发布到node.js

时间:2018-10-13 05:11:35

标签: javascript node.js swift

我知道之前已经解决了这个问题,但是我已经花了数小时,并且似乎无法弄清楚如何将数据发布到node.js服务器...我已经使用cloud9和node启动了该项目.js,所以我知道我安装得很好,并且我从一个工作站点开始。

我正在迅速发送一个发帖请求

func post (){
    let url = URL(string: "https://the-game-stevens-apps.c9users.io/index.html/")!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let postString = "name=henry&message=HelloWorld"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(error)")
            return
        }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }
        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }
    task.resume()
}

然后在我的server.js文件中

  var router = express();
  router.use(express.urlencoded());
  router.post('/index.html', function(req, res) {
     var obj = {name:req.body.name,text:req.body.message};
  });

我有很多使用javascript的经验,但是对于node.js来说我是一个菜鸟,并且一直在研究它,真的很感谢任何帮助

1 个答案:

答案 0 :(得分:0)

我可以在您的node.js代码中唯一纠正的部分是

要获取路由器,您需要致电express.Router();

  const express = require('express');
  const router = express.Router();
  router.use((req,res,next) => {
      console.log("/" + req.method,  "host"+ req.host, "Params" + req.params);
      next();
  });

  router.post('/index.html', (req, res) => {
         const obj = {name:req.body.name,text:req.body.message};
        //insert obj into database
  });