运行后端服务器时匿名的函数



我正在尝试为某些产品创建路由函数。主屏幕工作正常(显示所有产品),但我正在尝试添加功能,以便当用户单击产品时,它会自动重定向到提取有关该产品信息的页面。

当我运行后端服务器(npm start)时,我在终端中得到这个,当我点击我的产品时,会出现一个未定义的响应:

[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): backend/**/*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `babel-node backend/server.js`
serve at http://localhost:5000 [Function (anonymous)]

我尝试过几次浏览我的代码并尝试一些东西,看看函数是否有问题,但看不到问题。

这是我服务器的代码.js:

import express from 'express';
import cors from 'cors';
import { products } from './data.js';
const app = express();
app.use(cors());
app.get('/api/products', (_req, res) => {
res.send(products);
});
app.get('/api/products/:id')
app.listen(5000, () => {
console.log('serve at http://localhost:5000', (req, res) => {
const product = data.products.find((x) => x._id === req.params.id)
if (product) {
res.send(product);
} else {
res.status(404).send({ message: 'Product Not Found' })
}
})
});

这是我的配置.js:

import axios from 'axios'
import { apiUrl } from "./config"

export const getProduct = async (id) => {
try {
const response = await axios({
url: `${apiUrl}/api/products/${id}`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
if (response.statusText !== 'OK') {
throw new Error(response.data.message);
}
return response.data;
} catch (err) {
console.log(err);
return { error: err.message }
}
};

我刚刚包括了我的实用程序.js和下面的产品屏幕代码,只是为了更好地了解我在做什么,但是我认为问题出在服务器.js或配置.js。

util.js:

export const parseRequestUrl = () => {
const url = document.location.hash.toLowerCase();
const request = url.split('/');
return {
resource: request[1],
id: request[2],
action: [3],
};
}

产品屏幕.js

import { getProduct } from '../api';
import { parseRequestUrl } from '../util'
const ProductScreen = {
render: async () => {
const request = parseRequestUrl();
const product = await getProduct(request.id);
return `<h1>${product.name}</h1>`;
}
}
export default ProductScreen;

您实际上是通过提供函数作为第二个参数来打印带有console.log函数。将处理程序函数移动到相应的路由处理程序以进行/api/products/:id,如下所示:

import express from 'express';
import cors from 'cors';
import { products } from './data.js';
const app = express();
app.use(cors());
app.get('/api/products', (_req, res) => {
res.send(products);
});
// The handler function is moved here from `listen` callback.
app.get('/api/products/:id', (req, res) => {
const product = data.products.find((x) => x._id === req.params.id);

if (product) {
res.send(product);
} else {
res.status(404).send({ message: 'Product Not Found' });
}
})
app.listen(5000, () => {
console.log('serve at http://localhost:5000');
});

最新更新