我正在为 Next.js 应用程序开发一个小型 REST API。如果我将我的放在route.tsrootDir -> app -> api -> hello -> route.ts 中,如下所示,那么它可以工作:
//route.ts
export async function GET(request: Request) {
return new Response('Hello, Next.js!')
}
Run Code Online (Sandbox Code Playgroud)
我可以通过 Postman 向 localhost:3000/api/hello 发出成功的 GET 请求。
我现在将代码更改为以下内容:
import { NextApiRequest, NextApiResponse } from "next";
export async function GET(request: NextApiRequest, response: NextApiResponse) {
return response.json({ message: "Hello, Next.js!" });
}
Run Code Online (Sandbox Code Playgroud)
现在它失败了,我收到错误消息:
error TypeError: response.json is not a function
Run Code Online (Sandbox Code Playgroud)
该问题是已知的,但升级到最新的 lts 或最新的节点版本并不能解决我的问题: https: //github.com/vercel/next.js/issues/48524。
旁注我使用以下代码连接到数据库:
const mongoose = require('mongoose');
const connectDB = (url) => {
return mongoose.connect(url);
}
Run Code Online (Sandbox Code Playgroud)
问题描述:
我有两个不同的集合。这两个操作,findByIdAndUpdate并且create必须作为原子操作运行。这对于猫鼬交易来说应该是可能的。
const registerCustomer = async (req, res) => {
await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true });
const customer = await Customer.create({firstName: req.body.firstName});
}
Run Code Online (Sandbox Code Playgroud)
我尝试过的:
const registerCustomer = async (req, res) => {
const session = await mongoose.startSession();
await session.startTransaction();
try {
await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true }); //updates even though
const customer = await Customer.create({ firstName: req.body.firstName });// this line will …Run Code Online (Sandbox Code Playgroud)