IBM-Watson 助手 - 加载资源失败:服务器响应状态为 404(未找到)

IBM-Watson assistant - Failed to load resource: the server responded with a status of 404 (Not Found)

我正在尝试将 IMB-Watson 助手集成到我的 React 应用程序中,按照此处描述的这些步骤进行操作:IBM cloud API docs/Watson-assistant 在服务器端,首先我必须获取会话 ID,但我总是收到错误:

我的文件夹结构:

这是我的文件: server.js

const express = require("express");
const app = express();
require("dotenv").config();

app.use(express.json());

const watsonRoutes = require("./routes/api/watson");
app.use("/api/watson", watsonRoutes);

const port = process.env.PORT || 9000;
app.listen(port, () => {
  console.log("Server listening on port ", port);
});

watson.js

// 1. Import dependencies
const express = require("express");
const router = express.Router();
const AssistantV2 = require("ibm-watson/assistant/v2");
const { IamAuthenticator } = require("ibm-watson/auth");

// 2. Create Instance of Assistant

// 2.1 First authenticate
const authenticator = new IamAuthenticator({
  apikey: process.env.WATSON_ASSISTANT_APIKEY,
});

// 2.2 Connect to assistant
const assistant = new AssistantV2({
  version: "2020-04-01",
  authenticator: authenticator,
  url: process.env.WATSON_ASSISTANT_URL,
});

// 3. Route to Handle Session Tokens
// GET /api/watson/session
router.get("/session", async (req, res) => {
  // If successs
  try {
    const session = await assistant.createSession({
      assistantId: process.env.WATSON_ASSISTANT_ID,
    });
    res.json(session["result"]);

    // If fail
  } catch (err) {
    res.send("There was an error processing your request.");
    console.log(err);
  }
});

// 4. Handle Messages
// POST /api/watson/message
router.post("/message", async (req, res) => {
  // Construct payload
  payload = {
    assistantId: process.env.WATSON_ASSISTANT_ID,
    sessionId: req.headers.session_id,
    input: {
      message_type: "text",
      text: req.body.input,
    },
  };

  // If successs
  try {
    const message = await assistant.message(payload);
    res.json(message["result"]);

    // If fail
  } catch (err) {
    res.send("There was an error processing your request.");
    console.log(err);
  }
});

// 5. Export routes
module.exports = router;

> reactchatbot@1.0.0 dev /Users/seldaali/Downloads/ReactChatBot
> concurrently "npm run server" "npm run client"

[0] 
[0] > reactchatbot@1.0.0 server /Users/seldaali/Downloads/ReactChatBot
[0] > nodemon server
[0] 
[1] 
[1] > reactchatbot@1.0.0 client /Users/seldaali/Downloads/ReactChatBot
[1] > npm start --prefix client
[1] 
[0] [nodemon] 2.0.7
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching path(s): *.*
[0] [nodemon] watching extensions: js,mjs,json
[0] [nodemon] starting `node server.js`
[1] 
[1] > client@0.1.0 start /Users/seldaali/Downloads/ReactChatBot/client
[1] > react-scripts start
[1] 
[0] Server listening on port  9000
[1] ℹ 「wds」: Project is running at http://192.168.1.5/
[1] ℹ 「wds」: webpack output is served from 
[1] ℹ 「wds」: Content not from webpack is served from /Users/seldaali/Downloads/ReactChatBot/client/public
[1] ℹ 「wds」: 404s will fallback to /
[1] Starting the development server...
[1] 
[1] Browserslist: caniuse-lite is outdated. Please run the following command: `yarn upgrade`
[1] Compiled with warnings.
[1] 
[1] src/reducers/watson.js
[1]   Line 17:3:  Assign arrow function to a variable before exporting as module default  import/no-anonymous-default-export
[1] 
[1] Search for the keywords to learn more about each warning.
[1] To ignore, add // eslint-disable-next-line to the line before.
[1] 
[0] Forbidden: Access is denied due to invalid credentials.
[0]     at RequestWrapper.formatError (/Users/seldaali/Downloads/ReactChatBot/node_modules/ibm-cloud-sdk-core/lib/request-wrapper.js:275:21)
[0]     at /Users/seldaali/Downloads/ReactChatBot/node_modules/ibm-cloud-sdk-core/lib/request-wrapper.js:260:45
[0]     at processTicksAndRejections (internal/process/task_queues.js:93:5)
[0]     at async /Users/seldaali/Downloads/ReactChatBot/routes/api/watson.js:53:21 {
[0]   statusText: 'Forbidden',
[0]   status: 403,
[0]   code: 403,
[0]   body: '{"error":"Forbidden","trace":"c4570338-d808-4900-9427-000113cb13e1","code":403}',
[0]   headers: {
[0]     'strict-transport-security': 'max-age=31536000; includeSubDomains;',
[0]     'content-length': '80',
[0]     'content-type': 'application/json',
[0]     'x-dp-watson-tran-id': 'c4570338-d808-4900-9427-000113cb13e1',
[0]     'x-request-id': 'c4570338-d808-4900-9427-000113cb13e1',
[0]     'x-global-transaction-id': 'c4570338-d808-4900-9427-000113cb13e1',
[0]     server: 'watson-gateway',
[0]     'x-edgeconnect-midmile-rtt': '140',
[0]     'x-edgeconnect-origin-mex-latency': '7',
[0]     date: 'Fri, 15 Jan 2021 15:56:51 GMT',
[0]     connection: 'close'
[0]   }
[0] }

错误

Forbidden: Access is denied due to invalid credentials.

表示您使用了错误的密钥,或者该密钥与您使用的端点不匹配。

Watson 服务文档描述了如何生成 IAM 密钥 - https://cloud.ibm.com/docs/watson?topic=watson-iam

生成后,请检查您的端点,因为您需要将其添加到您的代码中。参见 https://cloud.ibm.com/apidocs/assistant/assistant-v2?code=python#service-endpoint

例如

assistant.set_service_url('https://api.us-east.assistant.watson.cloud.ibm.com')