从Next.js在Vercel Edge运行时的API路由,概念API,例如:检索数据库或查询数据库,响应400 invalid_request_url如下:
{"object":"error","status":400,"code":"invalid_request_url","message":"Invalid request URL."}
从本地环境(next dev
,vercel dev
), Notion API正确响应200。
代码如下:
检索数据库
import { NextRequest } from 'next/server'
export const config = { runtime: 'edge' }
async function(req: NextRequest) {
const url = `https://api.notion.com/v1/databases/${DATABASE_ID}`
const headers = {
'Authorization': `Bearer ${NOTION_API_SECRET}`,
'Notion-Version': '2022-06-28',
'Content-Type': 'application/json',
}
const response = await fetch(url, {
method: 'GET',
headers: headers,
})
const data = await response.json()
console.log(JSON.stringify(data))
}
查询数据库
import { NextRequest } from 'next/server'
export const config = { runtime: 'edge' }
async function(req: NextRequest) {
const { searchParams } = new URL(req.url);
if (!searchParams.has('slug')) {
throw new Error('No slug in searchParams.')
}
const slug = searchParams.get('slug').trim()
const url = `https://api.notion.com/v1/databases/${DATABASE_ID}/query`
const body = JSON.stringify({
filter: {
and: [
{ property: 'Published', checkbox: { equals: true } },
{ property: 'Slug', rich_text: { equals: slug } },
],
},
})
const headers = {
'Authorization': `Bearer ${NOTION_API_SECRET}`,
'Notion-Version': '2022-06-28',
'Content-Type': 'application/json',
}
const response = await fetch(url, {
method: 'POST',
body: body,
headers: headers,
})
const data = await response.json()
console.log(JSON.stringify(data))
}
NOTION_API_SECRET
和DATABASE_ID
设置正常。
200的期望,但不是。
我做了如下尝试:
- 对其他API(如https://jsonplaceholder.typicode.com/)的请求是OK的
- 尝试
export const config = { runtime: 'experimental-edge' }
但是400 - 尝试边缘运行时命令行在本地是OK的(200)
我使用节点包有同样的问题,我将我的功能从边缘切换回正常,部署时它正在工作。
export default async function handler(req, res) {
const response = await getPosts();
const scheme = response.scheme;
const items = response.items;
res.status(200).json({
scheme,
items,
})
}
getPosts()定义
import { Client, isFullDatabase } from "@notionhq/client";
import { type } from "os";
const notion = new Client({
auth: process.env.NOTION_SECRET,
});
const processDatabase = (database) => {
const notionDatabase = { scheme: "test", items: [] };
database.results.forEach((result) => {
const properties = result.properties;
const row = {
id: result.id,
data: {
name: properties.Name.title[0].plain_text,
author: properties.Author.rich_text[0].plain_text,
status: properties.Status.multi_select[0].name,
start_date: properties.Start.date?.start,
end_date: properties.End.date?.start,
},
};
notionDatabase.items.push(row);
});
return notionDatabase;
};
export async function getPosts() {
const response = await notion.databases.query({
database_id: "",
sorts: [
{
property: "Status",
direction: "ascending",
},
],
});
console.log(response);
return processDatabase(response);
}
我的边缘函数最后一次工作是在34天前部署到vercel。我的下一个任务是在26天前,不再工作,只回来500美元。从我的构建日志来看,所有的变化似乎是Vercel CLI版本从28.6.0到28.8.0,不确定这是否有关系。