next.js 当我在API目录中运行route.js时,我一直收到404错误

tkqqtvp1  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(121)

项目结构:


的数据
我有一个应该调用API函数的组件,但由于某种原因,似乎找不到该文件,我已确保正确设置了目录,并遵循了next.js项目设置。

CSVUploader.js:

'use client'

// components/CSVUploader.js
import { useState } from 'react';

export default function CSVUploader() {
    const [file, setFile] = useState(null);

    const handleFileChange = (e) => {
        setFile(e.target.files[0]);
    };

    const handleSubmit = async () => {
        const formData = new FormData();
        formData.append('file', file);

        const response = await fetch('/api/route', {
            method: 'POST',
            body: formData,
        });

        const data = await response.json();
        console.log(data);
    };

    return (
        <div>
            <input type="file" onChange={handleFileChange} />
            <button onClick={handleSubmit}>Upload and Process</button>
        </div>
    );
}

字符串

route.js

// pages/api/route.js
import { exec } from 'child_process';

export default async (req, res) => {
    if (req.method === 'POST') {
        // Assuming you're sending the CSV as text in the request body
        const csvData = req.body;

        // Save CSV data to a temporary file
        const tempFile = 'geofences_istak.csv';
        require('fs').writeFileSync(tempFile, csvData);

        // Run the Python script
        exec('python3 scripts/process_csv.py', (error, stdout, stderr) => {
            if (error) {
                console.error(`exec error: ${error}`);
                return res.status(500).json({ error: 'Failed to process the file.' });
            }

            // Respond with the result or the processed file location
            res.status(200).json({ data: stdout });
        });
    } else {
        res.status(405).end();  // Method Not Allowed
    }
};


但我得到的错误是


rkue9o1l

rkue9o1l1#

你只需要调用/api。请不要在api路径中包含route

const response = await fetch('/api', {
    method: 'POST',
    body: formData,
});

字符串
类似于不调用/page来渲染页面。

相关问题