检索数据意味着向您的节点端点发送 Get Request
由于我使用的是 axios,所以我建议你也使用 axios(如果你使用的是 react 或任何其他框架,请 npm install axios)或者你可以简单地复制它的脚本 CDN
您可以从前端简单地
axios.get("Your url address" + "api route address").then((response) => {
//do whatever with your response
}).catch(error => {
//Do something in case of error
})
以实际地址为例,假设我有一个节点服务器连接到在 localhost 8000 上运行的 mongoose,我的 api 端点看起来像这样(Backend)
我已经像这样导入了我的用户架构
const User = require("./../models/userSchema.js")
const User = require("./../models/userSchema.js")
router.get("/", async (req, res) => {
const contactList = await User.find({}) //coming from mongoose
res.send(contactList)
})
通过axios,我的api请求会是这样的(frontend)
axios.get("http://localhost:8000/").then((response) => {
后端部分 -> 发布请求
首先像这样定义和导出一个mongoose Schema
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
address: String,
email: {
type: String,
default: "www.xyz@abc.com"
},
number: Number,
OTP: Number,
createdAt: {type: Date, default: Date.now},
DateOfBirth: {
type: String,
default: "1/01/2001"
},
image: {
type: String,
default: "http://icons.iconarchive.com/icons/graphicloads/100-flat/256/contact-icon.png"
},
})
module.exports = mongoose.model("User", userSchema)
然后,希望您已经使用 MVC 模式配置了节点,将其导入到您需要使用模式的路由中
const express = require("express")
const router = express.Router()
const User = require("./../models/userSchema.js")
在该架构中创建一个接受发布请求(或放置请求)的 API 路由或端点
router.post("/message", async (req, res) => {
const newMessage = new User({
firstName: req.body.(whatever from your request contains firstName
.....
......
)}
})
一旦你填写了你得到的数据(req.body 包含数据)你需要保存它,在上面的路线上扩展
router.post("/message", async (req, res) => {
const newMessage = new User({
firstName: req.body.(whatever from your request contains firstName
.....
......
)}
newMessage.save().then((response) => {
if (error) {
console.log(error)
throw new Error (error)
} else {
console.dir(responseData)
res.send(responseData)
}
})
})
前端部分
由于我使用的是 axios,所以我建议你也使用 axios(如果你使用的是 react 或任何其他框架,则 npm install axios)或者你可以简单地复制它的脚本 CDN
在 axios 内部,我们发送 post 请求
axios.post("Your port address" + Message , object).then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})