我有一个带有 Express JS 的后端快递服务器
- 我的项目是通过config.js文件配置的
- 我在api.js中有一个正在运行的 API,它从 json 文件testData.json加载数据并将其返回给调用者。
- 在一个单独的文件serverRender.js中,我调用api.js中的端点来控制台记录它返回的 json 数据。
- 我正在从server.js调用serverRender.js并看到一个 ECONNREFUSED 错误,我认为它是 CORS 但不知道如何在这里解决它,并且从像这里这样的其他 stackoverflow 链接我没有得到太多
- 我试图从 curl 和 Web 浏览器访问http://0.0.0.0:8080/api/contests这是我的端点,两者似乎都有效。
非常感谢,任何建议。
配置.js
export default {
port: env.PORT || 8080,
host: env.HOST || '0.0.0.0',
get serverUrl() {
return `http://${this.host}:${this.port}`;
}
};
服务器.js
import express from 'express';
import config from './config';
import apiRouter from './api';
const server = express();
// Calling the api endpoint
import './serverRender';
server.get('/', (req, res) => {
res.send("hello world!")
});
// manage routes using the Express router
server.use('/api', apiRouter);
server.listen(config.port, config.host, () => {
console.log('Listening at ', config.serverUrl);
});
api.js
import express from 'express';
import data from '../src/testData.json';
const router = express.Router();
router.get('/contests', (req, res) => {
res.send({ contests: data.contests });
});
export default router;
测试数据.json
{
"contests": [
{
"id": 1,
"categoryName": "Business/Company",
"contestName": "Cognitive Building Bricks"
}
]
}
服务器渲染.js
import axios from 'axios';
import config from './config';
axios
.get(`${config.serverUrl}/api/contests`)
.then((resp) => {
console.log(resp.data);
})
.catch((error) => {
console.error
});
包.json
{
"name": "learn-fullstack-javascript",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "nodemon --exec babel-node server.js",
"dev": "webpack -w --mode=development",
"test": "echo \"Error: no test specified\" && exit 1"
},
"homepage": "https://github.com/jscomplete/learn-fullstack-javascript#readme",
"dependencies": {
"axios": "^0.26.0",
"ejs": "^3.1.6",
"express": "^4.17.2",
"mongodb": "^4.3.1",
"node-sass-middleware": "^0.11.0",
"prop-types": "^15.8.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"@babel/cli": "^7.17.0",
"@babel/core": "^7.17.2",
"@babel/node": "^7.16.8",
"@babel/plugin-proposal-class-properties": "^7.16.7",
"@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.16.7",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.3",
"eslint": "^8.8.0",
"eslint-plugin-react": "^7.28.0",
"json-loader": "^0.5.7",
"nodemon": "^2.0.15",
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2"
}
}