English 中文(简体)
如何将URL网页或主名登入下Js项目?
原标题:How to get page URL or hostname in NextJs Project?

我想接上全页的URL或像以下在Static站点发电机上的形象这样的网站主机。

我将尝试window. place.hostname,但我没有工作。

错误:window未定义。

“entergraph

问题回答

If you want the hostname inside getInitialProps on server side, still you can get it from req

Home.getInitialProps = async(context) => {
   const { req, query, res, asPath, pathname } = context;
   if (req) {
      let host = req.headers.host // will give you localhost:3000
     }
  }

With server-side rendering (getServerSideProps), you can use context.req.headers.host:

import type { GetServerSideProps, NextPage } from "next";

type Props = { host: string | null };

export const getServerSideProps: GetServerSideProps<Props> =
  async context => ({ props: { host: context.req.headers.host || null } });

const Page: NextPage<Props> = ({ host }) => <p>Welcome to {host || "unknown host"}!</p>;

export default Page;

但是,随着静态生成(getStaticProps),没有东道名称,因为没有要求从中获取。 一般而言,服务器不了解自己的公共托管人姓名,因此,你需要告知。 使用Next.js environment factors,将这一内容列入.env. local:

HOST=example.com

Then access it with process.env[ HOST ]:

import type { GetStaticProps } from "next";

export const getStaticProps: GetStaticProps<Props> = 
  async context => ({ props: { host: process.env[ HOST ] || null }});

If you want to get the full URL:

import { useRouter } from  next/router ;
const { asPath } = useRouter();
    const origin =
        typeof window !==  undefined  && window.location.origin
            ? window.location.origin
            :   ;

    const URL = `${origin}${asPath}`;
    console.log(URL);

The place where you are accessing the window make sure you add a check so that code is executed only on the browser and no during SSG"

if (typeof window !==  undefined ) {
   const hostname = window.location.hostname;
}

Update: If you have specified basePath in next.config.js:

module.exports = {
  basePath:  https://www.example.com/docs ,
}

然后使用<条码>用户

import { useRouter } from  next/router 

function Component() {
   const router = useRouter();
   
   console.log({ basePath: router.basePath}); 
   // { basePath:  https://www.example.com/docs  }

   ...
}

但是,如果你有相对的基路,你可以采用第一种方法。

Consider this package > next-absolute-url

import absoluteUrl from  next-absolute-url 
const { origin } = absoluteUrl(req)
const apiURL = `${origin}/api/job.js`

如果您在座尾随行,那么现在的缩略语将像

However, if you are running the app locally the apiURL will be http://localhost:8000/api/job.js instead.

使用<代码>窗口类型!=未界定的是安全的。

const hostname = typeof window !==  undefined  && window.location.hostname ? window.location.hostname :   ;
const origin = typeof window !==  undefined  && window.location.origin ? window.location.origin :   ;

采用上述代码后,用户名/边名/面名将贴上门:example.com,www.example.com,,等等,而不是 localhost enuff. >> useRouter(>>>>> 用户名/正本(< 当地编码>>>> /代码>,< 当地编码>> 当地编码>,< 代码>

我认为,通过<条码> 用户和<条码> 用户不适用,你能更好地做到这一点。 hoo。 在我的案件中,我想动态地制定我的网页og:url。 这就是我所做的。 我们有<条码>,即<>条码>,作为依附,因此,每当我们转向另一页时,都会更新<条码>。

import { useRouter } from "next/router";
import { useState, useEffect } from "react";

const MyComponent = () => {

  const router = useRouter();
  const [ogUrl, setOgUrl] = useState("");


  useEffect(() => {
    const host = window.location.host;
    const baseUrl = `https://${host}`;

    setOgUrl(`${baseUrl}${router.pathname}`);
  }, [router.pathname]);


  return <div></div>
}

您需要确保您能够进入<代码>window. 所在地。 东道名称<>/代码>只出现在客户方面,而不是在服务器提供期间(没有<代码>window)。 您可以通过将其移至<条码>(效应)来做到这一点。

function Component() {
    useEffect(() => {
        console.log(window.location.hostname) 
        console.log(window.location.href) // Logs `http://localhost:3000/blog/incididunt-ut-lobare-et-dolore`
    }, [])
    
    // Remaining code of the component
}

在这里,我是如何解决该问题的,这也与下届13号上诉路线者合作:

a. Create,称它使用原样。

 use client ; // this is Next 13 App Router stuff

import { useEffect, useState } from "react";

export default function useOrigin() {
  const [mounted, setMounted] = useState(false);
  const origin = typeof window !==  undefined  && window.location.origin ? window.location.origin :   ;

  useEffect(() => {
    setMounted(true)
  }, [])

  if (!mounted) {
    return null
  }

  return origin;
}

如今,利用这一 h,进入你动态的BASE_URL航道:

"use client";

import useOrigin from "@/hooks/use-origin"

export default function Test() {
  const origin = useOrigin();

  return (
    <div>{origin}</div>
  )
}

req.headers are Symbols and not Objects, so to get value, you use the get method

const host = req.headers.get("host"); // stackoverflow.com

以上答案都没有解决该问题,而解决办法就是:

function return_url(context) {
  if (process.env.NODE_ENV === "production") {
    // if you are hosting a http website use http instead of https
    return `https://${context.req.rawHeaders[1]}`;
  } else if (process.env.NODE_ENV !== "production") {
    return "http://localhost:3000";
  }
}

以及利用ServerSideProps或获得StaticProps的职能

export async function getServerSideProps(context) {
  let url = return_url(context);
  const data = await fetch(`${url}/yourEndPoint`).then((res) => res.json());
  return {
    props: {
      data: data,
    },
  };
}

如果有人想一想一帆风顺的话。

import { headers } from "next/headers";

export default function Page() {
  const headerList = headers();
  const domain = headerList.get("x-forwarded-host") || headerList.get("host") || "beta.popstarz.ai";
  console.log(domain);

  return (
    <main className="flex min-h-screen flex-col items-center justify-between py-3 pb-safe-bottom">
       ... 
    </main>
  );
}

in Next.js you can do like this, by useEffect to get window.location.origin in client side, and set it to state.

work fine in : { "next": "12.1.6", "react": "18.1.0", }

const Home: NextPage = () => {
  const { asPath, query } = useRouter();

  const [loading, setLoading] = useState(false);
  const [loginCallBackURL, setLoginCallBackURL] = useState("");
 
  useEffect(() => { 
      setLoginCallBackURL(
        `${window.location.origin}/${query.redirect ? query.redirect : "user"}`,
      ); 
  }, []);

  // if you do something like this, it can t get loginCallBackURL
  // const loginCallBackURL = useMemo(() => {
  //   if (typeof window !==  undefined ) {
  //     return `${window.location.origin}/${
  //       query.redirect ? query.redirect : "user"
  //     }`;
  //   }
  //   return asPath;
  // }, [asPath, query]);
 
  return (
    <div>
      <Button
        variant="contained" 
        href={queryString.stringifyUrl({
          url: `${publicRuntimeConfig.API_HOST}/auth/google/login`,
          query: {
            callbackURL: loginCallBackURL,
          },
        })}
      >
        Sign in with google
      </Button>
    </div>
  );
};

export default Home;





相关问题
Get domain name (not subdomain) in php

I have a URL which can be any of the following formats: http://example.com https://example.com http://example.com/foo http://example.com/foo/bar www.example.com example.com foo.example.com www.foo....

share a folder in 2 domains using .htaccess

I got 2 sub-domains c:wampwwwwebsiteA - http://websiteA/ c:wampwwwwebsiteB - http://websiteB/ inside websiteA got a folder for storing picture c:wampwwwwebsiteAphotos in order ...

Parsing Domainname From URL In PHP

How I can parse a domain from URL in PHP? It seems that I need a country domain database. Examples: http://mail.google.com/hfjdhfjd/jhfjd.html -> google.com http://www.google.bg/jhdjhf/djfhj....

ASP.NET MVC and ApplicationPath

Question is about paths and domains: I have an out-of-the box ASP.NET MVC project (generated by "File->New Project"). On LogOn page it does: return Redirect("~/Account/LogOn");. I have a domain ...

Finding if domain name is already registered? [closed]

Hi, Is there any API to lookup if a given domain name is already registerd by somebody and get alternative (auto suggested available domain names)? EDIT:- I think the thing I need is called domain-...

SQL: Sorting By Email Domain Name

What is the shortest and/or efficient SQL statement to sort a table with a column of email address by it s DOMAIN name fragment? That s essentially ignoring whatever is before "@" in the email ...

How to validate domain name in PHP?

Is it possible without using regular expression? For example, I want to check that a string is a valid domain: domain-name abcd example Are valid domains. These are invalid of course: domaia@name ...