Post请求服务器端Next Js

问题描述 投票:0回答:1

我对 React 和下一个 JS 还很陌生,我可以很好地执行服务器端获取请求,这非常简单。我只是想知道如何在 NextJs 服务器端执行对外部 api 的 post 请求,因为我不想在网络控制台中显示 api url,但我不知道如何做到这一点,因为使用正常程序我只需要将“使用客户端”放在页面顶部

这是我的正常发布请求登录代码,它工作得很好,但在网络选项卡中它显然是可利用的。

感谢大家的耐心等待

"use client"

import Link from "next/link"

import { Button } from "@/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useToast } from "@/components/ui/use-toast"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { ModeToggle } from "@/components/mode-toggle"
import { useDispatch } from 'react-redux';
import { loginSuccess } from '../redux/authSlice';


const  LoginForm = () => {

  

    const { toast } = useToast()
  const [error, setError] = useState("");
  const router = useRouter();
  
  
  const [formData, setFormData] = useState({
    
    username: '',
    password: ''
  });
  

  const handleInputChange = (event:any) => {
    const { name, value } = event.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = async (event:any) => {
    event.preventDefault(); 

    try {
      const response = await fetch('http://localhost:8080/api/auth/signin', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });
  
      const responseData = await response.json();
      
       
  
      // Verifica se la risposta contiene un messaggio di conferma
      if (responseData) {
        console.log('Login effettuato con successo!', responseData);
        localStorage.setItem('accessToken', responseData.token);
        localStorage.setItem('username', responseData.username);
        localStorage.setItem('isLoggedin', 'true');
        
        
        toast({
          description: "Login has been successful"
        })
        router.push('/');
        
        
        

        setFormData({
          
          username: '',
          password: ''
        });
        
      } else {
        // Altrimenti, la risposta non è come previsto
        console.error('La risposta dall\'API non è come previsto:', responseData);
        setError('Credenziali non valide. Si prega di riprovare.');
        
      }
  
    } catch (error) {
      
      console.error('Errore durante la registrazione:', error);
    }
  };
  return (
    <>
    <div className="toggle absolute top-5 right-5">
    <ModeToggle></ModeToggle>
    </div>
    
    <Card className="mx-auto my-auto max-w-sm ">
      <CardHeader>
        <CardTitle className="text-6x1 font-bold">Login</CardTitle>
        <CardDescription>
          Enter your email below to login to your account
        </CardDescription>
      </CardHeader>
      <CardContent>
      
      <form onSubmit={handleSubmit}>
      {error && <p style={{ color: 'red' }}>{error}</p>} {/* Visualizza l'errore se presente */}
        
      <Label>
        Username:
        <Input  type="text" name="username" value={formData.username} onChange={handleInputChange} />
      </Label>
      
      
      <Label>
        Password:
        <Input  type="password" name="password" value={formData.password} onChange={handleInputChange} />
      </Label>
      
      <Button className='mt-4 w-full' variant={"default"} type="submit"> Sign Up</Button>
      <p className="font-bold text-sm mt-4">You are not registered yet? <Link href="/register"><Button className="size-sm" variant={"link"}>Register</Button></Link></p>
      
      
    </form>
      </CardContent>
    </Card>
    </>
  )
}


export default LoginForm;
reactjs next.js server-side-rendering
1个回答
0
投票

签出getServerSideProps

示例


import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
 
type Repo = {
  name: string
  stargazers_count: number
}
 
export const getServerSideProps = (async () => {
  // Fetch data from external API
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const repo: Repo = await res.json()
  // Pass data to the page via props
  return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>
 
export default function Page({
  repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <main>
      <p>{repo.stargazers_count}</p>
    </main>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.