通过 API 创建用户时发生奇怪的事情

当我测试 API users.json 时,我使用 Postman 创建用户,操作成功,且默认处于激活状态,这意味着 active=true 是有效的。

但是,当我在 Node.js 中用代码创建用户时,即使参数相同,active=true 也不再生效。不过我确实收到了成功消息,显示:

success: true,
active: false

这是怎么回事?我甚至在后端都看不到相关记录。

我猜测您的 Node.js 代码没有正确传递 API 密钥,因此您无法覆盖 active 参数。如果您能在此处分享一段代码片段,我们或许能为您提供帮助。

嗨,David,谢谢:

这是我的请求:

{
 "url": "users.json",
 "method": "post",
 "data": {
      "api_key": "57d06a163190ee90de1118ac2adbaf5eeb5aa93d4d02dbe8f5d424c388f126e294c",
      "api_username": "Nathan001",
      "name": "tokgood",
      "email": "tokgood@qq.com",
      "password": "64c6457d-b815-4e87-8ea1-e66becd710bc",
      "username": "2cx9pyCMyn",
      "active": true,
      "approved": true
 },
 "headers": {
      "common": {
           "Accept": "application/json, text/plain, */*"
      },
      "delete": {},
      "get": {},
      "head": {},
      "post": {
           "Content-Type": "application/x-www-form-urlencoded"
      },
      "put": {
           "Content-Type": "application/x-www-form-urlencoded"
      },
      "patch": {
           "Content-Type": "application/x-www-form-urlencoded"
      },
      "content-type": "multipart/form-data"
 },
 "baseURL": "https://www.tuntry.com/",
 "transformRequest": [
      null
 ],
 "transformResponse": [
      null
 ],
 "timeout": 60000,
 "xsrfCookieName": "XSRF-TOKEN",
 "xsrfHeaderName": "X-XSRF-TOKEN",
 "maxContentLength": -1
}

我已经双重检查了 API 用户和密钥,确认无误。

我刚刚用 Axios 封装了一个 POST 请求。

   const post = (url, data) => service.post(url, {
   api_key: Config.discourse.api_key,
   api_username: Config.discourse.api_username,
  ...data,
 }
)

我对 Node.js 不太了解,但就我所见,这看起来没问题。

你可以尝试通过 HTTP 头而不是参数来发送 API 凭证。通过参数发送的方式已弃用,并且会在你的管理面板中引发警告。头名称为 Api-KeyApi-Username(注意是连字符,而不是下划线)。更多信息请参见 此处

太好了,是的,我在添加了 Api-KeyApi-Username,并在请求头中添加了 'content-type': 'application/json', 后解决了这个问题!