我想我在不理解的情况下从堆栈溢出中复制/粘贴代码出错了。
所以我想用正文快速创建一个发布请求。
正文包含键/值对(我是 swift 新手)。
在javascript中,我会做这样的事情
axios.post(url, {data:{"testConfigKey": "testing"}}
这就是我正在迅速做的事情
let url = URL(string: checkUserConfig)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = ["testConfigKey": "testing"] //not sure if this is correct
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // not sure if this is correct
} catch let error {
print(error.localizedDescription)
XCTFail("Unable to localize")
}
在我的后端,这是在我的请求正文中给出以下响应(console.log(req.body))
{ '{\n "testConfigKey" : "testing"\n}': '' }
这就是我的 api endopint 的样子
app.post("/checkUserConfig", async (req, res) => {
console.log(req.body)
let userConfig = req.body.testConfigKey;
console.log(userConfig)
res.status(200).send(userConfig);
});
我想要的是当我在我的后端 api 中做这样的事情时
let userConfig = req.body.testConfigKey;
它应该给我"testing"
我基本上参考了这个答案stackoverflow:https ://stackoverflow.com/a/41082546/10433835
有人可以帮我弄清楚我做错了什么吗?