首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Notion.so API在本地开发应用程序时总是抛出CORS错误。

Notion.so API在本地开发应用程序时总是抛出CORS错误。
EN

Stack Overflow用户
提问于 2022-10-15 18:22:45
回答 1查看 161关注 0票数 -1

今天,我面临着一个问题,任何在实习生身上找到的解决方案都无法解决这个问题。

我试图创建一个博客应用程序使用惊人的Notion.so笔记应用程序。当然,对于这些东西,我需要他们的API。

在用React代码实现之前,我测试了失眠症中的所有东西(邮递员,比如app)。一切都很顺利。

当我开始在react-redux中实现第一个请求时.砰,一切都毁了。

这就是提出要求的地方:

代码语言:javascript
复制
export const notionApi = createApi({
  reducerPath: "notionApi",
  baseQuery: fetchBaseQuery({
    baseUrl: "https://api.notion.com/v1",
    prepareHeaders: headers => {
      headers.set("Authorization", process.env.REACT_APP_NOTION_SECRET);
      headers.set("Notion-Version", " 2022-02-22");
      return headers;
    }
  }),
  endpoints: builder => ({
    getMenu: builder.query({
      query: id => `/blocks/${id}/children`
    })
  })
});

export const { useGetMenuQuery } = notionApi;

这是在浏览器中:

代码语言:javascript
复制
Access to fetch at 'https://api.notion.com/v1/blocks/c5886e5e15d04d4bb8112bafcec8475b/children' from 
origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight 
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is 
present on the requested resource. If an opaque response serves your needs, set the 
request's mode to 'no-cors' to fetch the resource with CORS disabled.

信不信由你,我什么都试过了: Cors Chrome应用程序模仿,CRA代理在package.json,快递服务器模仿代理和5个小时的绝望搜索。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-17 09:43:09

首先感谢Shahriar在评论中给出的宝贵建议。到目前为止,执行概念的API的唯一变体是代理。下面是我如何使Notion.so API在浏览器中工作的方式。

首先,我启动了一个Express服务器。

代码语言:javascript
复制
// server.js

const app = express();
const server = http.createServer(app);

app.use(express.json());
app.use(cors());

app.get('/getmenu', async (req, res) => {
  const data = await NotionApi('uuid');
  res.status(200).json(data);
});


const PORT = process.env.PORT || 5000;
server.listen(PORT, console.log(`Server started @ ${PORT}`));

使用axios,我创建了函数来调用概念API:

代码语言:javascript
复制
// utils/NotionApi.js

require('dotenv').config();
const axios = require('axios');

async function NotionApi(id) {
  return await axios
    .get(`https://api.notion.com/v1/blocks/${id}/children`, {
      headers: {
        Authorization: `Bearer ${process.env.NOTION_SECRET}`,
        'Notion-Version': ' 2022-02-22',
      },
    })
    .then(async (res) => {
      return res.data;
    })
    .catch((err) => {
      NotionApi = undefined;
      console.log(err);
    });
}

module.exports = NotionApi;

然后我把这美丽的东西部署到了赫罗库和瓦利亚!

需要概念的项目url:https://jsadvanced.github.io/

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74081980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档