2017-11-08 7 views
0

こんにちは皆さんはnode.jsエクスプレスと一緒にSwift 4(以下のコードを入力してください)からnode.jsサーバーへのポストリクエストで値を送るのに問題がありますxcodeで次のエラーが表示されます。サーバーに接続できませんでした。 localhostでnode.jsを使ってテストしましたが、誰でも助けてくれますか?ありがとう。Swift 4からNode.jsへのポストリクエストを送信

スウィフト機能:あなたは、デバイスまたはシミュレータ上で実行している場合の

@IBAction func LoginFunction(_ sender: Any) { 

    // prepare json data 
    let json: [String: Any] = ["title": "ABC", 
           "dict": ["1":"First", "2":"Second"]] 

    let jsonData = try? JSONSerialization.data(withJSONObject: json) 

    // create post request 
    let url = URL(string: "http://localhost:3000/login")! 
    var request = URLRequest(url: url) 
    request.httpMethod = "POST" 

    // insert json data to the request 
    request.httpBody = jsonData 

    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
     guard let data = data, error == nil else { 
      print(error?.localizedDescription ?? "No data") 
      return 
     } 
     let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) 
     if let responseJSON = responseJSON as? [String: Any] { 
      print(responseJSON) 
     } 
    } 

    task.resume() 


} 

サーバーのNode.js

'use strict' 

const express = require('express') 
const bodyParser = require('body-parser') 

// Create a new instance of express 
const app = express() 

// Tell express to use the body-parser middleware and to not parse extended bodies 
app.use(bodyParser.urlencoded({ extended: false })) 

// Route that receives a POST request to /sms 
app.post('/login', function (req, res) { 
  const body = req.body.Body 
  res.set('Content-Type', 'text/plain') 
  res.send(`You sent: ${body} to Express`) 
}) 

// Tell our app to listen on port 3000 
app.listen(3000, function (err) { 
  if (err) { 
    throw err 
  } 

  console.log('Server started on port 3000') 
}) 
+0

[http:// localhost:3000/login](http:// localhost:3000/login)を試したことがありますか? –

+0

@FrancescoDeliroはい試しましたが動作しません – riki

+0

plistファイルに任意の負荷を許可するように設定しましたか?あなたのサーバーは動作していますか?デフォルトでは、httpsのトラフィックは許可されていません。httpトラフィックを許可するにはplistに設定する必要があります – Scriptable

答えて

1

まず、それが依存します。 デバイス上で実行している場合は、localhostがデバイスを指しているため、ローカルホスト経由でサーバにアクセスすることはできません。シミュレータ上で実行する場合にのみlocalhostを使用できます。デバイスで実行している場合は、コンピュータのプライベートIPを指定する必要があります。ここ は、あなたのIPアドレスを印刷し、コピーします迅速なシェル方法である:

ifconfig en0 | awk '/inet.[0-9]/ {print "\033[1m \033[31m"$2 }' && ifconfig en0 | awk '/inet.[0-9]/ {printf $2}' | pbcopy -pboard general 

だけの端末でこれを貼り付けると、すべての

セカンドを入力打つあなたが任意のロードを有効にする必要があるため、これはあるかもしれませんあなたのアプリ、http呼び出しはiOS 9以上でデフォルトでブロックされています ここであなたがこれを行う方法です:https://stackoverflow.com/a/40299837/2252297

希望に役立ちます。

+0

ありがとうございます – riki

関連する問題