我的節點應用程式中有這個最小的設定:
服務器.js
/**
* Starting point for the backend
*/
'use strict'
const app = require('./app');
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
} else {
console.log("Production mode is on");
}
const port = process.env.NODE_LOCAL_PORT;
const host = process.env.HOST;
app.listen(port, () => {
console.log(`Server is listening on http://${host}:${port} `);
});
應用程式.js
'use strict'
const express = require('express');
require('dotenv').config();
require('express-async-errors');
/* Spaceholder for routes */
const availabilityRoutes = require('./routes/availability');
const inventoryRoutes = require('./routes/inventory');
const overviewRoutes = require('./routes/overview');
const utilisationRoutes = require('./routes/utilisation');
const app= express();
app.use(express.json());
// For testing purpose
const routes = express.Router();
routes.get('/test', async(req, res, next) => {
console.log("test");
res.send("test");
});
/* Register the modules containing the routes */
app.use(process.env.PUBLIC_URL '/api/availability', availabilityRoutes);
app.use(process.env.PUBLIC_URL '/api/inventory', inventoryRoutes);
app.use(process.env.PUBLIC_URL '/api/overview', overviewRoutes);
app.use(process.env.PUBLIC_URL '/api/utilisation', utilisationRoutes);
app.use((req,res,next) => {
res.sendStatus(404);
});
module.exports = app;
/api/availability 的示例控制器
const express = require('express');
const routes = express.Router();
const cors = require('cors');
const helper = require('../helper');
const allowedOrigins = ['http://localhost:3000', 'http://localhost:4000'];
//delete for prod or test env
const whitelist = {
origin: function(origin, callback) {
if(origin && allowedOrigins.indexOf(origin) == -1){
let errorMsg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(errorMsg), false);
}
//for calls from the same host the browser do not put the origin
return callback(null, true);
}
}
//global for the entire module
const queries = helper.readJSONfile();
routes.get('/', cors(whitelist), async(req, res, next) => {
console.log("Hello");
res.send("Hello");
helper.getApiCall(req, res, queries.availability.overview);
});
依賴:
"@influxdata/influxdb-client": "^1.14.0",
"@influxdata/influxdb-client-apis": "^1.14.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.9"
即使我想打電話,http://localhost:4000/test我也會回傳 404“Not Found”,我不知道為什么。
uj5u.com熱心網友回復:
你應該使用app.get() 而不是routes.get()
uj5u.com熱心網友回復:
先生,您使用了一個發送狀態代碼 404 的中間件,這就是它不起作用的原因。這個 :
app.use((req,res,next) => {
res.sendStatus(404);
});
從 get 開始,當它移動到這個中間件時,它已經發送了一個狀態碼。我可能錯了,我現在也在學習,如果我錯了,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324648.html
標籤:javascript 节点.js 表达
上一篇:使用類別在物件中添加數量
