我想向本地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格式?