简体   繁体   English

如何在next.js中获取全浏览器url,getServerSideProps

[英]How to get full browser url in next js, getServerSideProps

Now, i'm in http://localhost:3000/ , but on prod i will be in a different url, for example http://example.com/ , how can i get full browser url in getServerSideProps?现在,我在http://localhost:3000/ ,但在产品上我将在不同的 url,例如http://example.com/ ,我如何在 getServerSideProps 中获得完整的浏览器 url? I have to get http://localhost:3000/ or http://example.com/ , if string will not contain port, it will be ok我必须得到http://localhost:3000/http://example.com/ ,如果字符串不包含端口,就可以了

And in the additional answer you use in this my case:在我的案例中使用的附加答案中:

export const getServerSideProps = async (
  context: GetServerSidePropsContext
) => {
  const { req } = context;
  let url = req.headers.referer;
  let arr = url.split('/');
  url = `${arr[0]}//${arr[2]}`;

This URL gives you for example http://localhost:3000 enjoy!这个URL给你例如http://localhost:3000 enjoy!

'next/router' provide a couple of methods too, which you can use. 'next/router' 也提供了一些方法,您可以使用它们。 For example:例如:

import { useRouter } from 'next/router';

const RouterObject = () => {
  const { asPath, pathname, req, query, res } = useRouter();
  console.log(asPath);
  console.log(pathname); 
  console.log('host: ', req.headers.host);
}

If you have the host you can check if contains localhost.如果您有主机,您可以检查是否包含本地主机。 Then you know you are in your local environment.然后你知道你在你的本地环境中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Next.js 如何获取ServerSideProps - Next.js how to getServerSideProps 如何使用 getServerSideProps 在 Next JS 中添加分页 API - how to add pagination API in Next JS with getServerSideProps 如何在下一个 js 中的 getserversideprops 中应用过滤器和分页 - How To apply filters and pagination in getserversideprops in next js 如何使用下一个 js 加速 getServerSideProps? - How to speed up getServerSideProps with next js? 在 Next.js getServerSideProps 中,如何从浏览器获取 cookie 以识别用户 - In Next.js getServerSideProps, how can I fetch cookie from browser to identify the user Next.js - 如何在客户端上使用 fetch get 查询获取 getServerSideProps 中的反应 - Next.js - How to get the reaction in getServerSideProps using fetch get query on client 如何在 Next.JS 中使用 getServerSideProps 从条带 api 获取用户数据? - How can I get user data from the stripe api with getServerSideProps in Next.JS? 如何在getServerSideProps next js中访问更新的redux store state? - How to access updated redux store state in getServerSideProps next js? 如何在 Next.js 的 getServerSideProps 方法中使用 cookie? - How to use cookie inside `getServerSideProps` method in Next.js? 如何访问 Next.js 中 getServerSideProps 中的查询参数? - How to access query params inside getServerSideProps in Next.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM