[英]How to do api calls without fetch in nextjs?
I have a nextjs project with express backend that requires some data fetching in getServerSideProps
.我有一个带有 express 后端的 nextjs 项目,需要在getServerSideProps
中获取一些数据。
The problem is await fetch('/api/anyApi')
doesnt work with relative path and calls to absolute path await fetch('${config.OPTION_HOST}/api/anyApi'
are getting blocked by some kind of protection on host machine. I wish to fix this problem instead and just use absolute paths but Ive been told thats not possible right now so I need to rewrite getServerSideProps
everywhere to not use fetch
.问题是await fetch('/api/anyApi')
用于相对路径,并且对绝对路径的调用await fetch('${config.OPTION_HOST}/api/anyApi'
被主机上的某种保护阻止。我希望解决这个问题,只使用绝对路径,但我被告知现在不可能,所以我需要在任何地方重写getServerSideProps
以不使用fetch
。
Best solution I could find without rewriting big chunk of backend logic was to use mocks like in this anwser在不重写大量后端逻辑的情况下,我能找到的最佳解决方案是使用类似这个 anwser中的模拟
So instead of const result = await fetch('/api/menu/${context.locale}')
I end up with this code:因此,而不是const result = await fetch('/api/menu/${context.locale}')
我最终得到以下代码:
export async function getServerSideProps(context) {
const categoryController = require('../../../server/controllers/category')
var MockExpressRequest = require('mock-express-request');
var MockExpressResponse = require('mock-express-response');
var requestMenu = new MockExpressRequest( {
params: {
locale: context.locale,
}
})
var responseMenu = new MockExpressResponse();
await categoryController.getCategories(requestMenu, responseMenu);
const result = responseMenu
...rest of getServerSideProps...
}
Im new to programing and while this solution works, I have a feeling that using a library for testing in producion code might be bad idea.我是编程新手,虽然这个解决方案有效,但我觉得使用库来测试生产代码可能是个坏主意。 What do you think?你怎么看?
You could use AXIOS instead: https://www.npmjs.com/package/axios您可以使用 AXIOS 代替: https://www.npmjs.com/package/axios
You can find all the AXIOS documentation here: https://axios-http.com/您可以在此处找到所有 AXIOS 文档: https://axios-http.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.