json - 尝试使用 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 格式?
解决方案
推荐阅读
- macos - 如何在 MAC OS X Catalina 上的 WebDAV 中为每个人定义权限
- python - 无法在 Google colab 中加载 spaCy 模型
- git - 将远程(主)分支重新定位到特定提交
- r - Ifelse 以多列中的相同字符串为条件
- hibernate - 如何从休眠中调用具有自定义数据库类型作为参数的存储过程?
- javascript - 如何在数据表中从 '2021-01-09T00:00:00' LIKE 2021-01-09 转换日期时间格式
- python - 循环遍历 Python 中的变量名称
- wordpress - img_caption_shortcode 的实现没有效果
- c# - Protobuf 无法序列化 system.object
- python - 在 Python Pandas 中,为什么 .describe 和 .describe() 给出不同的结果?