首页 > 解决方案 > 尝试使用 Swift 在 Xcode 中使用 POST 请求将 json 格式的数据发送到本地 Web 服务器

问题描述

我想向本地 Web 服务器发送 POST 请求,并将格式为 JSON 的数据发送到服务器。这是我的代码:

 @IBAction func postTapped(_ sender: Any) {
    let parameters = ["id": "id_number", "name": "user_name"]

    let jsonUrlString = "http://localhost:5000"
    guard let url = URL(string: jsonUrlString) else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
        else { return }



    request.httpBody = httpBody

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
            //print(httpBody)
        }

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options:[])
                print(json)
            } catch {
                print(error)
            }
        }
        }.resume()
}

但是我收到一个错误,在 Xcode 的调试控制台中显示以下内容:

   { Status Code: 404, Headers {
Connection =     (
    "keep-alive"
);
"Content-Length" =     (
    140
);
"Content-Security-Policy" =     (
    "default-src 'self'"
);
"Content-Type" =     (
    "text/html; charset=utf-8"
);
Date =     (
    "Mon, 28 Jan 2019 03:05:29 GMT"
);
"X-Content-Type-Options" =     (
    nosniff
);
"X-Powered-By" =     (
    Express
);
  } }
  Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

这是我的 Express 代码(index.js 文件):

   const express = require('express');
  const app = express();

   app.use(express.json());

   const users = [
  { id: 1, name: 'jordan' },
  { id: 2, name: 'toshi'},
  { id: 3, name: 'jyrone'},

  ];
  app.get('/', (req, res) => {
res.send('Hello World Im ya muthafuckin trouble maker!!!');
 });

   app.get('/api/user', (req, res) => {
   res.send(users);
  });

   app.post('/api/user', (req, res) => {
if (!req.body.name || req.body.name.length < 3) {
    // 400 Bad Request
    res.status(400).send('Name is not long enough or invalid');
    return;
   };

const user = {
    id: users.length + 1,
    name: req.body.name
};
users.push(user);
res.send(user);
console.log(user);
});


  app.get('/api/user/:id', (req, res) => {
const user = users.find(c => c.id === parseInt(req.params.id));
if (!user) res.status(404).send('The user with given id was not found');
res.send(user);
 });

 // PORT
  const port = process.env.PORT || 5000;
  app.listen(port, () => console.log(`Listening on port ${port}...`));

如何解决此问题,以便服务器将 POST 请求数据显示为 JSON 格式?

标签: jsonswiftapiexpresspost

解决方案


推荐阅读