英文:
NextJS req.url is giving wrong URL
问题
我已经在产品卡片上设置了一个链接,指向'/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000',并且在自定义产品页面[product].js中,我正在调用服务器端API(使用SSR),我需要将URL传递给后端以获取产品详细信息。为了做到这一点,我需要访问当前URL,nextjs在SSR中提供的是{req.url},在我的情况下,我在本地主机上得到的输出是'/_next/data/development/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000.json?product=hansgrohe-croma-100-shower-set-100-4jet-vario-27592000'。在开发服务器中,这可能会起作用,但我如何在本地主机中获取实际的URL?
const fullUrl = req.url;
console.log(fullUrl); // 打印这个 '_next/data/development/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000.json?product=hansgrohe-croma-100-shower-set-100-4jet-vario-27592000'
英文:
I have set a link on product card to '/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000' and in the custom product page [product].js I am calling the server side API (using SSR) I have to pass the url to backend to fetch the product detail. In order to do that I need access to current URL which nextjs gives as {req.url} in SSR, In my case I am getting output as '/_next/data/development/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000.json?product=hansgrohe-croma-100-shower-set-100-4jet-vario-27592000' in localhost. In dev server it might work but how do I get the actual URL in localhost?
const fullUrl = req.url;
console.log(fullUrl); // Prints this '/_next/data/development/en/product/hansgrohe-croma-100-shower-set-100-4jet-vario-27592000.json?product=hansgrohe-croma-100-shower-set-100-4jet-vario-27592000'
答案1
得分: 1
我不确定您的要求,但您可以使用getServerSideProps函数的context参数来访问请求对象及其属性,如headers、query、params等。
例如:
export async function getServerSideProps(context) {
const req = context.req;
const host = req.headers.host;
const path = context.params.product;
const query = context.query;
const fullUrl = `http://${host}/product/${path}?${query}`;
console.log(fullUrl);
return {
props: {},
};
}
英文:
I'm not sure of your requirements but you can use the context parameter of the getServerSideProps function to access the request object and its properties, such as headers, query, params, etc.
For example:
export async function getServerSideProps(context) {
const req = context.req;
const host = req.headers.host;
const path = context.params.product;
const query = context.query;
const fullUrl = `http://${host}/product/${path}?${query}`;
console.log(fullUrl);
return {
props: {},
};
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论