我對執行程式沒有任何問題。我對兩個引數在檔案中的不同位置以及它們的關系有疑問。我有一個 html 檔案:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Registration</h1>
<form id="reg-form">
<input type="text" id="username" autocomplete="off" placeholder="Username">
<input type="password" id="password" autocomplete="off" placeholder="Password">
<input type="submit" value="Submit Form">
</form>
<script>
const form = document.getElementById('reg-form')
form.addEventListener('submit', registerUser)
async function registerUser(event){
event.preventDefault()
const username = document.getElementById('username').value
const password = document.getElementById('password').value
const result = await fetch('/api/register',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
username,
password
})
}).then((res)=>res.json())
console.log(result)
}
</script>
</body>
</html>
我有一個 js 檔案:
const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
const User = require('./model/user')
const bcrypt = require('bcrypt')
mongoose.connect('mongodb://localhost:27017/login-app-db',{
useNewUrlParser:true,
useUnifiedTopology:true
})
const app = express()
app.use('/', express.static(path.join(__dirname, 'static')))
app.use(express.json())
app.post('/api/register', async(req,res)=>{
console.log(req.body)
res.json({status:'ok'})
})
app.listen(9999,()=>{
console.log('Server up at 9999')
})
當我單擊時,我有一個按鈕,它向我顯示了在終端中使用 console.log 輸入的用戶名和密碼中的值。
但我不明白的地方是
const result = await fetch('/api/register'
和
app.post('/api/register', async(req,res)=>
哪個先處理,那個“/api/register”實際上是什么。當我單擊按鈕時,它是否是在 html 和 js 之間提供通信的組成路徑,如果它是如何在后面作業的?
uj5u.com熱心網友回復:
在您的 Node.js 代碼中,您創建一個 Express 服務器并設定請求處理程式,這app.post('/api/register' ...)是其中之一。
在您的客戶端代碼中,當您呼叫 時fetch('/api/register', ...,瀏覽器會發出請求http://<your-domain>/api/register并處理回應(如果有)。
Express 是一個 Web 服務器框架,它構建在 Node.js http 模塊之上,并在路由方面提供了大量實用程式。每當服務器在正確的埠上接收到傳入請求時,它都會通過將其方法和路徑與處理程式中的方法和路徑進行比較來過濾匹配您擁有的所有處理程式。如果找到匹配的處理程式,它將被執行,并使用作為引數傳遞的請求物件進行呼叫。在您的情況下,任何POST請求都http://<your-domain>/api/register將由該處理程式處理。(您可以在此處閱讀有關 Express 路由的更多資訊)
/api/register確實只是一個虛構的路徑,它為您的 Web 應用程式 API 提供了一個結構并強制執行了一個介面約定——它本來可以被很好地稱為/signupor /api/user/registration。但是,人們在構建它們時通常會遵循 REST 架構風格,其中路徑將定義系統中的資源,方法將定義應用于資源的操作型別。也就是說,只要在系統的所有部分(即客戶端代碼和服務器代碼)中強制執行約定,您就可以以任何對您最有意義的方式自由設計 API。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/336048.html
標籤:javascript 节点.js 表达 邮政 拿来
上一篇:我是nodejs的新手,我想從html檔案路由一個頁面,但它不起作用---Nodejs路由問題
下一篇:無法更新學生資料
