如何在Next js API路由中设置Response的header内容类型

bksxznpy  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(120)

我使用Next.js 14应用路由器.我想动态创建一个XML文件时,API路由被调用,并发送它在响应.这里是我的代码:

export async function GET(req: NextApiRequest, res: NextApiResponse) {
  try {

    // Set response to XML
    //   res.setHeader("Content-Type", "text/xml");

    // Send the XML file to the browser.
     return res.send("my xml string"));

  } catch (err) {
    console.error(err);
    return new Response(JSON.stringify(err), { status: 500 });
  }
}

字符串
编译器不会给予错误,但是当调用API时,它会抛出一个错误:res.setHeaders()不是一个函数

sc4hvdpw

sc4hvdpw1#

在Next.js API路由中,您应该使用res.setHeader()方法来设置响应头,包括用于发送XML的“Content-Type”头。
以下是Next.js API路由的正确代码:

import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    // Set the response content type to XML
    res.setHeader('Content-Type', 'text/xml');

    // Create your XML content (replace this with your actual XML generation logic)
    const xmlString = generateXML(); // Replace generateXML with your XML generation function

    // Send the XML as the response
    return res.send(xmlString);
  } catch (err) {
    console.error(err);
    return res.status(500).json({ error: err.message });
  }
}

// Replace generateXML with your XML generation function
function generateXML() {
  // Implement your XML generation logic here
  // For example:
  return '<root><element>Some XML data</element></root>';
}

字符串

相关问题