javascript - 尝试从我自己的 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
);
});
解决方案
推荐阅读
- codenameone - 有没有办法减少代号中手风琴的高度?
- c++ - 使用可变参数模板(或类似机制)将类型列表传递给函数
- java - 排序数组 - 任何人都可以帮我解决我失败的地方吗?
- javascript - 带有缓冲区的 WMS GetFeatureInfo 请求不返回任何结果(OpenLayers/MapServer)
- r - R: group_id 通过改变行值
- javascript - 我将如何在 buttonclick 上运行一个选项并向该选项添加一个功能
- json - 使用 PowerShell 解析 JSON 数组
- python - Python - colorsys.hsv_to_rgb 返回一个浮点值
- java - 如何连接不仅仅依赖于自己的存储库的服务?
- typescript - TypeScript:在定义 @typescript-eslint/no-use-before-define 之前使用了“handleFirstTab”