我得到的问题是每次我尝试任何代码,我得到这个错误:
“文件路径”中没有导出HTTP方法。为每个HTTP方法导出命名导出。
下面是我的route.ts文件:
import type { NextApiRequest, NextApiResponse } from 'next';
const apiKey = "";
// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
const inputPath = 'public/CodeGeneration.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));
axios({
method: 'post',
url: 'https://api.remove.bg/v1.0/removebg',
data: formData,
responseType: 'arraybuffer',
headers: {
...formData.getHeaders(),
'X-Api-Key': apiKey,
},
encoding: null
})
.then((response: any) => {
if(response.status != 200) return console.error('Error:', response.status, response.statusText);
fs.writeFileSync("no-bg.png", response.data);
})
.catch((error: any) => {
return console.error('Request failed:', error);
});
这是我的page.tsx文件:
"use client";
import { useState } from 'react';
const BackgroundRemovalPage = () => {
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [resultPath, setResultPath] = useState<string | null>(null);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
setFile(event.target.files[0]);
} else {
console.warn('No files selected');
}
};
const handleUpload = async () => {
if (!file) return;
setLoading(true);
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', file);
try {
const response = await fetch('/api/backgroundRemover', {
method: 'POST',
body: formData,
});
if (response.ok) {
const data = await response.json();
setResultPath(data.path);
} else {
console.error('Upload failed:', response.statusText);
}
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
};
return (
<div>
<input type="file" accept="image/*" onChange={handleFileChange} />
<button onClick={handleUpload} disabled={!file || loading}>
{loading ? 'Processing...' : 'Remove Background'}
</button>
{resultPath && <img src={resultPath} alt="Result" />}
</div>
);
};
export default BackgroundRemovalPage;
我试过使用不同的API,试过创建组件并调用它们,试过让ChatGPT为我重写它,看看是否能发现任何问题。
不知道是什么引起的。
1条答案
按热度按时间w80xi6nr1#
route.ts
文件不正确。你需要在里面定义一个Route Handler,比如:支持以下HTTP方法:GET、POST、PUT、PATCH、DELETE、HEAD和OPTIONS。如果调用了不支持的方法,Next.js将返回405 Method Not Allowed响应。
https://nextjs.org/docs/app/building-your-application/routing/route-handlers