小编Las*_*zlo的帖子

JS:如何通过重定向功能将url传递给登录功能

在我的React/nextJS应用程序中,我正在检查getInitialProps静态函数中的有效令牌.我正在使用它作为HOC - 但在这种情况下这应该不重要.

如果令牌无效(或丢失),则用户将被重定向到登录页面.这是通过redirect如下所示的功能完成的.到现在为止还挺好.

如何将用户重定向到的页面的URL传递给登录组件?

如果用户未登录并正在调用http://my-server.com/any-page之类的内容,则会将其重定向到索引页面(http://my-server.com):将会有登录名形成.如果登录成功,我想将他重定向回第一个被调用页面:http://my-server.com/any-page

  1. 将受限制的页面调用为未登录的用户
  2. 重定向到索引登录页面
  3. 登录后重定向回1页.

我不知道如何将这些信息传递给登录功能......

与服务器,props.js

export default WrappedComponent =>
  class extends Component {
    static async getInitialProps (context) {
      const { req, pathname } = context
      let isValid = false

      if (req && req.headers) {
        const cookies = req.headers.cookie
        if (typeof cookies === 'string') {
          const cookiesJSON = jsHttpCookie.parse(cookies)
          initProps.token = cookiesJSON['auth-token']
          if (cookiesJSON['auth-token']) {
            jwt.verify(cookiesJSON['auth-token'], secret, (error, decoded) => {
              if (error) { …
Run Code Online (Sandbox Code Playgroud)

javascript redirect node.js reactjs next.js

10
推荐指数
1
解决办法
1092
查看次数

如何使用测试库测试下一个/脚本?

我的 React 组件<script>使用 nextJS 渲染标签Head。当尝试使用测试库的方法查询元素时getByTestId,我收到以下消息:

TestingLibraryElementError: Unable to find an element by: [data-testid="keen-to-test"]
Ignored nodes: comments, <script />, <style />
Run Code Online (Sandbox Code Playgroud)

有没有办法包含script在输出中,或者我应该使用不同的策略来验证我的脚本是否已注入?提前致谢

成分

import Head from 'next/head';

const FancyScript = ({src}) => {
  if (src) {
   return (
     <Head>
      <script
        data-testid="keen-to-test"
        type="text/javascript"
        async
        src={src}
      </script>
     </Head>
   )
  }
  return null;
}
Run Code Online (Sandbox Code Playgroud)

测试

import { render } from '@testing-library/react';
import FancyScript from '/fancy-location';

it('return some fancy', () => {
    const { getByTestId } = …
Run Code Online (Sandbox Code Playgroud)

reactjs next.js react-testing-library testing-library

6
推荐指数
1
解决办法
4408
查看次数