我想接上全页的URL或像以下在Static站点发电机上的形象这样的网站主机。
我将尝试window. place.hostname
,但我没有工作。
错误:window未定义。
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.
根据此处提及的“swer”,您可使用以下代码,利用新的名录(服务器侧部分)在接下来的13处获得东道方名:
import { headers } from next/headers ;
export default function Home() {
const headersList = headers();
headersList.get( host ); // to get domain
headersList.get( next-url ); // to get url
return <div>....</div>
}
NOTE:请指出: 在布局或网页上加以使用,将选择一条途径,在提出请求时能够动态地提供。
使用<代码>窗口类型!=未界定的是安全的。
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
借助你在项目根基中添加的“>文档,你可以查阅东道国的名称,并根据需要灵活地采取行动。
https://nextjs.org/docs/advanced-features/middleware
// Example: redirecting a domain to a subdomain
import { NextResponse } from "next/server";
// This function can be marked `async` if using `await` inside
export function middleware(request) {
// Currently there is no main site so we redirect to the subdomain.
const host = request.headers.get("Host");
if (
process.env.NODE_ENV === "production" &&
host.startsWith("mydomain.com")
) {
return NextResponse.redirect(new URL("https://mysubdomain.mydomain.com"));
} else if (
process.env.NODE_ENV === "staging" &&
host.startsWith("staging.mydomain.com")
) {
return NextResponse.redirect(
new URL("https://mysubdomain-staging.mydomain.com")
);
}
}
AFAIK有两种方式:
下一份联合材料为我们提供了useRouter hook,首先,你必须将其进口到你的部件中,然后使用路标,你只得宣布。 例如:
2. 管道 = 使用者;
console.log (router.pathname);
const {pathname} = router; <---- To access the pathname directly.
此外,正如“Xairoo”以前所说的那样,如果你想要使用窗户,你必须检查<代码>window!=未界定的,以避免错误。
以上答案都没有解决该问题,而解决办法就是:
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;
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....
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 ...
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....
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 ...
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-...
We re developing an application that is sensitive to the domain name of the request. The problem we re running into is that we have to use IIS in order to test the application because Cassini will ...
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 ...
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 ...