首页 > 解决方案 > 尝试从我自己的 API 获取数据时出现“未定义”

问题描述

如果我的问题没有使用正确的术语,请原谅,我仍然是 Web 开发的初学者。

我正在构建一个 chrome 扩展,它从当前选项卡中提取一个值,然后通过我单独构建的 Web API 查询我的 PostgreSQL 数据库。当我将fetch与我的 API 一起使用时,我得到确认我已成功连接到 API,但我得到的结果是undefined。我希望有人能帮助我吗?

我觉得这可能与Access-Control-Allow-Origin有关,但我真的需要一些指导。

提前致谢!

接口:

包.json

{
  "name": "postgres_api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "pg": "^8.5.1"
  }
}

index.js

const express = require("express");
const app = express();
const pool = require("./db");

app.use((req, res, next) => {
  res.header(
    "Access-Control-Allow-Origin",
    "chrome-extension://XXXXXXXXXXXXXXXXXX"
  );
  next();
});

app.use(express.json()); // => req.body

app.get("/bamboo/:product", async (req, res) => {
  const { product } = req.params;
  console.log(product);

  try {
    const getProducts = await pool.query(
      `SELECT * FROM products WHERE product_name like '%${product}%'`
    );
    const final_data = res.json(getProducts.rows);
    console.log(final_data);
    return final_data;
  } catch (err) {
    console.error(err.message);
  }
});

铬扩展:

清单.json

{
  "name": "name",
  "description": "description",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": ["activeTab", "tabs"],
  "action": {
    "default_title": "Bamboo",
    "default_popup": "popup.html",
    "default_icon": "/images/icon.png"
  },
  "icons": {
    "128": "/images/icon.png"
  }
}

脚本.js

function isEmptyOrSpaces(str) {
  return str == null || str.trim() === "";
}

// let tab_title = "";
function display_search(results) {
  const search = results[0];

  if (isEmptyOrSpaces(search)) {
    document.querySelector(".search-results").textContent =
      "No input detected...";
  } else {
    document.querySelector(".search-results").textContent =
      "We found 7 items similar to '" + search + "'...";

    fetch(`http://localhost:8080/bamboo/${search}`)
      .then(() =>
        console.log(
          `API connected successfully: http://localhost:8080/bamboo/${search}`
        )
      )
      .then((res) => console.log(res)) // ******** this is where i'm getting undefined ********
      .catch((err) => console.error("Something went wrong:", err));
  }
}

chrome.tabs.query({ active: true }, function (tabs) {
  let tab = tabs[0];
  // tab_title = tab.title;
  chrome.tabs.executeScript(
    tab.id, // id of the tab in which to run the script
    {
      code: 'document.querySelector("#twotabsearchtextbox").value',
    },
    display_search
  );
});

标签: javascriptnode.jspostgresqlexpressgoogle-chrome-extension

解决方案


推荐阅读