![](/img/trans.png)
[英]when running node with express gives me 'cannot GET' error in the browser
[英]Troubleshooting ‘Cannot GET /’ Error when running ‘Example Backend’ in Node
我正在嘗試運行Codecademy課程“設置 Postman - 學習快速路線”中的“示例后端”作為我作為后端工程師的路徑的一部分。 但是,當我嘗試在瀏覽器中訪問它時,我收到一條錯誤消息,內容為“
不能獲取 /。
我的node版本是v16.19.0,已經安裝了npm和Espress。 還有其他人遇到過這個錯誤嗎? 我該如何解決這個問題?
package.json
{
"name": "example_backend",
"version": "1.0.0",
"description": "A simple backend server to test out API requests",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Codecademy",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"express": "^4.18.2",
"sqlite3": "^5.1.4"
}
}
服務器.js
const express = require('express');
const bodyParser = require('body-parser');
const { initDB } = require('./db');
// Initialize the express app
const app = express();
// Use the body-parser middleware to parse the request body as json
app.use(bodyParser.json());
// Initialize the database
const db = initDB();
// Route to retrieve all users
app.get("/users", (req, res) => {
// Select all users from the 'users' table
db.all("SELECT * FROM users", [], (err, rows) => {
if (err) {
// If there is an error, send a 500 status code with the error message
res.status(500).json({"error": err.message});
} else {
// Otherwise, send the rows as the response
res.json({users: rows})
}
});
});
// Route to retrieve a specific user by id
app.get("/users/:id", (req, res) => {
// Get the id from the request params
const { id } = req.params;
// Select the user with the specified id from the 'users' table
db.all("SELECT * FROM users where id is (?)", [id], (err, rows) => {
if (err) {
// If there is an error, send a 500 status code with the error message
res.status(500).json({"error": err.message});
} else if (rows.length === 0) {
// If no user is found, send an empty object as the response
res.json({user: {}})
} else {
// Otherwise, send the first row as the response
res.json({user: rows[0]})
}
})
});
// Route to create a new user
app.post("/users", (req, res) => {
// Get the username and password from the request body
const { user: { username, password} } = req.body;
// The insert statement for the 'users' table
const insertStmt = "INSERT INTO users(username,password) VALUES (?,?)";
db.run(insertStmt, [username, password], function(err, result) {
if (err) {
// If there is an error, send a 500 status code with the error message
res.status(500).json({ "error": err.message });
} else {
// Otherwise, send the newly created user object as the response
res.json({
id: this.lastID,
username,
password
})
}
})
});
// Start the server on port 4000
app.listen(4000, () => console.log("Simple server running on http://localhost:4000"))
數據庫.js
const sqlite3 = require("sqlite3");
// Address for the in-memory database
const DB_ADDR = ":memory:";
// Sample data for the 'users' table
const users = [
{
username: "1lameuser",
password: "secret_password"
},
{
username: "cool_user_87",
password: "notPassword!"
},
];
/**
* Initializes the database with the 'users' table and sample data
*/
const initDB = () => {
// Create a new in-memory database
const db = new sqlite3.Database(DB_ADDR);
// Serialize the database operations to prevent concurrent writes
db.serialize(() => {
// Create the 'users' table
db.run(`CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT
)`);
// Prepare the insert statement for the 'users' table
const insertStmt = db.prepare("INSERT INTO users(username,password) VALUES (?,?)");
// Insert the sample data into the 'users' table
users.forEach(({ username, password}, i) => {
insertStmt.run([username, password]);
})
// Finalize the insert statement
insertStmt.finalize();
});
return db;
};
module.exports = { initDB };
您在 Express 應用中定義了3 條路線:
GET /users
GET /users/:id
POST /users
當服務器收到請求時,它會嘗試將請求 HTTP 方法(例如 POST\GET)和請求路徑(例如 /users/:id)匹配到路由。
如您所見,沒有路由與 HTTP 方法 GET 和路徑 / 的請求相匹配,這就是您收到錯誤的原因。
要測試它,請嘗試將以下路由添加到您的應用程序並再次調用它。 此路由將匹配具有路徑 / 的 GET 請求
app.get('/', (req, res) => {
res.sendStatus(200)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.