错误[ERR_HTTP_HEADERS_SENT]:在将标头发送到nextJS中的客户端后,无法设置标头

v2g6jxz6  于 2022-10-21  发布在  其他
关注(0)|答案(1)|浏览(104)

代码运行正常,并重定向到条带结账页面,但在部署后,它没有。我在尝试结账时得到状态500,但购物车项目和金额在条带日志中发布,状态为Payed。
错误[ERR_HTTP_HEADERS_SENT]:无法在将标头发送到客户端后设置标头错误[ERR_HTTP_HEADERS_SENT]:在新节点上将标头发送到客户端后无法设置标头在服务器响应时出现错误(节点:内部/错误:387:5)。在节点NextResponse.setHeader(节点:_HTTP_Out:603:11)上的错误(Node:_HTTP_Out:603:11)位于NodeNextResponse.setHeader(C:\Users\subash\OneDrive\Desktop\ecommerce\ecommerce\node_modules\next\dist\server\base-http\node.js:56:19)
以下是代码
Lib/getStripe.js

import {loadStripe} from '@stripe/stripe-js';

let stripePromise;

const getStripe = () => {
    if(!stripePromise){
        stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
    }
    return stripePromise;
}

export default getStripe;

Cart.js

const handleCheckout = async () => {
    const stripe = await getStripe();

    const response = await fetch('/api/stripe', {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(cartItems)
    });

    if (response.statusCode === 500) return;
    const data = await response.json();

    toast.loading("Redirecting...");
    stripe.redirectToCheckout({ sessionId: data.id });
  };

Pages/api/stripe.js

import Stripe from 'stripe';

const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY);

export default async function handler(req, res) {
  if (req.method === 'POST') {

    try {
      // Create Checkout Sessions from body params.
      const params = {
        submit_type :'pay',
        mode:'payment',
        payment_method_types:['card'],
        shipping_address_collection: {
            allowed_countries: ['IN'],
        },
        shipping_options: [
            {shipping_rate: '...'}
        ],
        line_items: req.body.map((item)=>{
            const img = item.image[0].asset._ref;
            const newImage = img.replace('image-','https://cdn.sanity.io/..../').replace('-webp','.webp');
            return {
                price_data:{
                    currency:'inr',
                    product_data:{
                        name:item.name,
                        images:[newImage],
                    },
                    unit_amount:item.price*100,
                },
                adjustable_quantity:{
                    enabled:true,
                    minimum:1
                },
                quantity:item.quantity
            }
        }),
        success_url: `${req.headers.origin}/success`,
        cancel_url: `${req.headers.origin}`,
      }
      const session = await stripe.checkout.sessions.create(params);

      res.status(200).json(session);
      res.redirect(303, session.url);
    } catch (err) {
      res.status(err.statusCode || 500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    console.log("error");
    res.status(405).end('Method Not Allowed');
  }
}
hrysbysz

hrysbysz1#

您仍然在使用遗留的Checkout与redirectToCheckout的集成,而应该查看可以找到here的Next.js的新集成路径。如果您想了解更多关于从遗留集成进行迁移的信息,可以查看Checkout迁移指南here

相关问题