Next.js Discord

Discord Forum

405 (Method Not Allowed)

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
When I try submitting data with a fetch post request I get this error. Here is my code:

const formData = new FormData();
formData.append('resume', resumeFile);

// Use axios for file upload
const response = await fetch('/api/analyze_resume', {
method: 'POST',
body: formData,
});

45 Replies

Asian black bearOP
import grammar from 'grammar-check';
import multer from 'multer';

// Set up multer for handling file uploads
const upload = multer();

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
      try {
      // Use multer to handle the file upload
      upload.single('resume')(req, res, async function (err) {
        if (err) {
          console.error(err);
          return res.status(500).json({ error: 'File upload failed' });
        }

        // Access the resume file text from the request object
        const resumeText = req.file?.buffer.toString('utf8') || '';

        // Check spelling and grammar
        const grammarCheckResult = grammar.check(resumeText);

        // Analyze other criteria
        const isValid = analyzeResumeCriteria(resumeText);

        res.status(200).json({ isValid, grammarCheckResult });
      });
    } catch (error) {
      console.error(error, "test");
      res.status(500).json({ error: 'Internal Server Error Test' });
    }
  } else {
    // Handle any other HTTP method
  }
}

function analyzeResumeCriteria(resumeText) {
  // Your existing logic for analyzing resume criteria
  const isOnePage = resumeText.split('\n').length <= 30;
  const bulletPointsRegex = /(?:^|\n)\s*[-\u2022•]\s*/g;
  const bulletPointsCount = (resumeText.match(bulletPointsRegex) || []).length;
  const hasMinimumBulletPoints = bulletPointsCount >= 3;
  const hasDatesForAllJobs = true; // Implement your logic for checking dates

  return isOnePage && hasMinimumBulletPoints && hasDatesForAllJobs;
}
@Ray could you show the code on `/api/analyze_resume'`?
Asian black bearOP
I have sent the code
@Asian black bear import grammar from 'grammar-check'; import multer from 'multer'; // Set up multer for handling file uploads const upload = multer(); export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'POST') { try { // Use multer to handle the file upload upload.single('resume')(req, res, async function (err) { if (err) { console.error(err); return res.status(500).json({ error: 'File upload failed' }); } // Access the resume file text from the request object const resumeText = req.file?.buffer.toString('utf8') || ''; // Check spelling and grammar const grammarCheckResult = grammar.check(resumeText); // Analyze other criteria const isValid = analyzeResumeCriteria(resumeText); res.status(200).json({ isValid, grammarCheckResult }); }); } catch (error) { console.error(error, "test"); res.status(500).json({ error: 'Internal Server Error Test' }); } } else { // Handle any other HTTP method } } function analyzeResumeCriteria(resumeText) { // Your existing logic for analyzing resume criteria const isOnePage = resumeText.split('\n').length <= 30; const bulletPointsRegex = /(?:^|\n)\s*[-\u2022•]\s*/g; const bulletPointsCount = (resumeText.match(bulletPointsRegex) || []).length; const hasMinimumBulletPoints = bulletPointsCount >= 3; const hasDatesForAllJobs = true; // Implement your logic for checking dates return isOnePage && hasMinimumBulletPoints && hasDatesForAllJobs; }
are you using app router or page router and what is the path of this route?
Asian black bearOP
I dont know
ok what is the path for the api route?
Asian black bearOP
the path is /api/analyze_resume
the file path
is it inside a pages folder or app folder
Asian black bearOP
app/pages/api
ok so it is app router
Asian black bearOP
ok
@Asian black bear ok
import grammar from 'grammar-check';
import multer from 'multer';

// Set up multer for handling file uploads
const upload = multer();

export function POST(req: Request) {
  try {
    // Use multer to handle the file upload
    upload.single('resume')(req, res, async function (err) {
      if (err) {
        console.error(err);
        return res.status(500).json({ error: 'File upload failed' });
      }

      // Access the resume file text from the request object
      const resumeText = req.file?.buffer.toString('utf8') || '';

      // Check spelling and grammar
      const grammarCheckResult = grammar.check(resumeText);

      // Analyze other criteria
      const isValid = analyzeResumeCriteria(resumeText);

      return Response.json({ isValid, grammarCheckResult })
    });
  } catch (error) {
    console.error(error, "test");
    return Response.json({ error: 'Internal Server Error Test' }, {status: 500})
  }
}


function analyzeResumeCriteria(resumeText) {
  // Your existing logic for analyzing resume criteria
  const isOnePage = resumeText.split('\n').length <= 30;
  const bulletPointsRegex = /(?:^|\n)\s*[-\u2022•]\s*/g;
  const bulletPointsCount = (resumeText.match(bulletPointsRegex) || []).length;
  const hasMinimumBulletPoints = bulletPointsCount >= 3;
  const hasDatesForAllJobs = true; // Implement your logic for checking dates

  return isOnePage && hasMinimumBulletPoints && hasDatesForAllJobs;
}

try this code
Asian black bearOP
Now I get:
POST http://localhost:3000/api/analyze_resume 500 (Internal Server Error)
500 error
then check your server console for the error from console.error(error, "test");
Asian black bearOP
TypeError: s is not a function
@Asian black bear TypeError: s is not a function
should be something wrong with grammar-check or multer
Asian black bearOP
Ok I used chatgpt to generate this code
ah
Asian black bearOP
How do I find what is causing the error?
@Asian black bear How do I find what is causing the error?
try comment out the code for grammar-check and just return a empty object
Asian black bearOP
ok
if it work then should be related to multer
Asian black bearOP
still getting a 500 error
but I think you don't need multer there, You can just use form
Asian black bearOP
ok
how do I change my code
Even when I comment out all the multer and grammar code I still get an error
Asian black bearOP
I commented out those packages:

// import grammar from 'grammar-check';
// import multer from 'multer';

// // Set up multer for handling file uploads
// const upload = multer();

export function POST(req: Request) {
  try {
    return Response.json({ })
    // Use multer to handle the file upload
    // upload.single('resume')(req, res, async function (err) {
    //   if (err) {
    //     console.error(err);
    //     return res.status(500).json({ error: 'File upload failed' });
    //   }

    //   // Access the resume file text from the request object
    //   const resumeText = req.file?.buffer.toString('utf8') || '';

    //   // Check spelling and grammar
    //   // const grammarCheckResult = grammar.check(resumeText);

    //   // Analyze other criteria
    //   const isValid = analyzeResumeCriteria(resumeText);

    //   return Response.json({ })
    // });
  } catch (error) {
    console.error(error, "test");
    return Response.json({ error: 'Internal Server Error Test' }, {status: 500})
  }
}


function analyzeResumeCriteria(resumeText) {
  // Your existing logic for analyzing resume criteria
  const isOnePage = resumeText.split('\n').length <= 30;
  const bulletPointsRegex = /(?:^|\n)\s*[-\u2022•]\s*/g;
  const bulletPointsCount = (resumeText.match(bulletPointsRegex) || []).length;
  const hasMinimumBulletPoints = bulletPointsCount >= 3;
  const hasDatesForAllJobs = true; // Implement your logic for checking dates

  return isOnePage && hasMinimumBulletPoints && hasDatesForAllJobs;
}
👀
should be someting wrong in the client code if you still get 500 with this
Asian black bearOP
"use client";
import React, { useState } from 'react';
import axios from 'axios';
import Head from 'next/head';
import { Navbar } from '../components/Navbar';
import styles from './dashboard.module.css';

const Dashboard = () => {
  const [resumeFile, setResumeFile] = useState(null);  // Update state to handle file
  const [reviewResult, setReviewResult] = useState(null);

  const handleFileChange = (e) => {
    // Update state when file input changes
    const file = e.target.files[0];
    setResumeFile(file);
  };

  const handleReview = async () => {
    try {
      // Create a FormData object to send the file
      const formData = new FormData();
      formData.append('resume', resumeFile);

      // Use axios for file upload
      const response = await fetch('/api/analyze_resume', {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      // Handle non-successful responses
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // Parse the response JSON
    const responseData = await response.json();

      // Set review result based on the response
      setReviewResult(responseData);
    } catch (error) {
      console.error("error", error);
      // Handle error appropriately
    }
  };

  return (
    <>
      <Head>
        <title>Career Coach</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Navbar />
      <div>
        <h1>Resume Reviewer</h1>
        {/* Use input type file for resume upload */}
        <input type="file" onChange={handleFileChange} />

        {/* Additional UI elements as needed */}
        <button onClick={handleReview}>Review Resume</button>

        {reviewResult && (
          <div>
            <p>Review Result:</p>
            <p>Is 1 page: {reviewResult.isValid ? 'Yes' : 'No'}</p>
            <p>Grammar and Spelling: {reviewResult.grammarCheckResult}</p>
          </div>
        )}
      </div>
    </>
  );
};

export default Dashboard;
Its from chatgpt
I dont think its wrong idk
@Asian black bear "use client"; import React, { useState } from 'react'; import axios from 'axios'; import Head from 'next/head'; import { Navbar } from '../components/Navbar'; import styles from './dashboard.module.css'; const Dashboard = () => { const [resumeFile, setResumeFile] = useState(null); // Update state to handle file const [reviewResult, setReviewResult] = useState(null); const handleFileChange = (e) => { // Update state when file input changes const file = e.target.files[0]; setResumeFile(file); }; const handleReview = async () => { try { // Create a FormData object to send the file const formData = new FormData(); formData.append('resume', resumeFile); // Use axios for file upload const response = await fetch('/api/analyze_resume', { method: 'POST', body: formData, }); if (!response.ok) { // Handle non-successful responses throw new Error(`HTTP error! Status: ${response.status}`); } // Parse the response JSON const responseData = await response.json(); // Set review result based on the response setReviewResult(responseData); } catch (error) { console.error("error", error); // Handle error appropriately } }; return ( <> <Head> <title>Career Coach</title> <link rel="icon" href="/favicon.ico" /> </Head> <Navbar /> <div> <h1>Resume Reviewer</h1> {/* Use input type file for resume upload */} <input type="file" onChange={handleFileChange} /> {/* Additional UI elements as needed */} <button onClick={handleReview}>Review Resume</button> {reviewResult && ( <div> <p>Review Result:</p> <p>Is 1 page: {reviewResult.isValid ? 'Yes' : 'No'}</p> <p>Grammar and Spelling: {reviewResult.grammarCheckResult}</p> </div> )} </div> </> ); }; export default Dashboard;
export async function POST(req: Request) {
  try {
    const data = await req.formData();
    const file = data.get("resume");
    if (file instanceof File) {
      const resumeText = Buffer.from(await file.arrayBuffer()).toString("utf8");

      // Check spelling and grammar
      const grammarCheckResult = grammar.check(resumeText);

      // Analyze other criteria
      const isValid = analyzeResumeCriteria(resumeText);

      return Response.json({ isValid, grammarCheckResult });
    }
    // Use multer to handle the file upload
  } catch (error) {
    console.error(error, "test");
    return Response.json(
      { error: "Internal Server Error Test" },
      { status: 500 },
    );
  }
}
@Asian black bear "use client"; import React, { useState } from 'react'; import axios from 'axios'; import Head from 'next/head'; import { Navbar } from '../components/Navbar'; import styles from './dashboard.module.css'; const Dashboard = () => { const [resumeFile, setResumeFile] = useState(null); // Update state to handle file const [reviewResult, setReviewResult] = useState(null); const handleFileChange = (e) => { // Update state when file input changes const file = e.target.files[0]; setResumeFile(file); }; const handleReview = async () => { try { // Create a FormData object to send the file const formData = new FormData(); formData.append('resume', resumeFile); // Use axios for file upload const response = await fetch('/api/analyze_resume', { method: 'POST', body: formData, }); if (!response.ok) { // Handle non-successful responses throw new Error(`HTTP error! Status: ${response.status}`); } // Parse the response JSON const responseData = await response.json(); // Set review result based on the response setReviewResult(responseData); } catch (error) { console.error("error", error); // Handle error appropriately } }; return ( <> <Head> <title>Career Coach</title> <link rel="icon" href="/favicon.ico" /> </Head> <Navbar /> <div> <h1>Resume Reviewer</h1> {/* Use input type file for resume upload */} <input type="file" onChange={handleFileChange} /> {/* Additional UI elements as needed */} <button onClick={handleReview}>Review Resume</button> {reviewResult && ( <div> <p>Review Result:</p> <p>Is 1 page: {reviewResult.isValid ? 'Yes' : 'No'}</p> <p>Grammar and Spelling: {reviewResult.grammarCheckResult}</p> </div> )} </div> </> ); }; export default Dashboard;
"use client";

import React, { useState } from "react";
import axios from "axios";
import Head from "next/head";
import { Navbar } from "../components/Navbar";
import styles from "./dashboard.module.css";

const Dashboard = () => {
  // Update state to handle file
  const [reviewResult, setReviewResult] = useState(null);

  const handleReview = async (e: React.FormEvent<HTMLFormElement>) => {
    try {
      // Create a FormData object to send the file
      const formData = new FormData(e.currentTarget);

      // Use axios for file upload
      const response = await fetch("/api/analyze_resume", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        // Handle non-successful responses
        throw new Error(`HTTP error! Status: ${response.status}`);
      }

      // Parse the response JSON
      const responseData = await response.json();

      // Set review result based on the response
      setReviewResult(responseData);
    } catch (error) {
      console.error("error", error);
      // Handle error appropriately
    }
  };

  return (
    <>
      <Navbar />
      <div>
        <h1>Resume Reviewer</h1>
        <form onSubmit={handleReview}>
          {/* Use input type file for resume upload */}
          <input type="file" name="resume" />

          {/* Additional UI elements as needed */}
          <button>Review Resume</button>
        </form>

        {reviewResult && (
          <div>
            <p>Review Result:</p>
            <p>Is 1 page: {reviewResult.isValid ? "Yes" : "No"}</p>
            <p>Grammar and Spelling: {reviewResult.grammarCheckResult}</p>
          </div>
        )}
      </div>
    </>
  );
};

export default Dashboard;
Asian black bearOP
It says syntax error on line 13
13 | const handleReview = async (e: React.FormEvent<HTMLFormElement>) => {
@Asian black bear 13 | const handleReview = async (e: React.FormEvent<HTMLFormElement>) => {
if not, change it to
const handleReview = async (e) => {
Asian black bearOP
I did that