Unable to make a POST request to the express API using the next.js API route (nextauth)

Currently, I have an express server running on port 8080 and my NextJS app running on port 3000. To handle user authentication, I am utilizing nextauth which involves sending username and password credentials to the express API on port 8080 for validation. However, I keep encountering a persistent 404 error when attempting to post to localhost:8080/api/public/signin, which is the designated endpoint for signing in through Express.

localhost:8080/api/public/signin

The file pages/api/auth/[...nextauth].js contains the following content:

export default NextAuth({
...
providers: [
  Providers.Credentials({
    name: "Email/Password",
    credentials: {
      email: { label: "Email", type: "text" },
      password: { label: "Password", type: "password" },
    },
    async authorize(credentials) {
      let user = await axios
        .post("localhost:8080/api/public/signin", {
          ...credentials,
         })
        .then((res) => res.data)
        .catch((e) => console.log("login failed", e));

    
      if (user && user.name && user.user_type) {
        return user;
      } else {
        throw new Error("Login failed. Please check email and password");
      }
    },
  })
]}

It is worth noting that the sign-in endpoint functions correctly when accessed via Postman or directly from a web page using a browser.

Answer №1

Did you consider including the protocol (http://) in your URL?

Axios may not support semi-absolute URLs like the one you provided. It's neither a relative URL (e.g. /api/public/signin) nor a full absolute URL.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to reference the className within nested SCSS when working with Next.js and React.js?

I am working on customizing a navbar that includes a hamburger button. My goal is to change the style, specifically the bar color and the appearance of the hamburger button, upon tapping. I have already attempted using &:active and .activeBar in the SCSS f ...

When modifying the state of an array within a component, certain values may be overwritten and lost in the process

Currently, I'm faced with the challenge of ensuring that a component displays a loading screen until all images have completed loading. This is necessary because there are approximately 25 images that must finish loading before the page can be display ...

Tips for fixing the Next.js installation error with yarn: Ensure that options.env['npm_config__p_a_c_k_a_g_e___l_o_c_k_'] is a string that does not contain null bytes

When attempting to create a Next.js app with yarn using "yarn create next-app", an error is thrown stating: An unexpected error occurred: "The property 'options.env['npm_config__p_a_c_k_a_g_e___l_o_c_k_']' must be a string without null ...

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

Enhance the app.get response by integrating data fetched from an http.get request

Currently, I am utilizing express and passing the path as a URL parameter. app.get("/download", function (req, res) { var location; var options = { host: 'example.com', port: 80, path: req.query.url.replace(/ /g, ...

Creating a Node.js API with Firebase Backend

Hey everyone, I wanted to get some advice on a project I'm working on. I've read a lot about setting up Node/Express with Firebase, but I'm curious about potential challenges when it comes to building and scaling a custom REST API using Fire ...

An Express Handlebars callback function is mandatory

Recently, I've been attempting to incorporate handlebars into my express project. However, I keep encountering an error in the node.exe console indicating that a callback function is needed. Can anyone offer some assistance with this issue? Here&apos ...

What is the best method to retrieve the transloadit final link stored on a file's storage server (such as Google Cloud Storage) and bring it back to the component?

Trying to understand how to retrieve the final link stored in Google Storage (starting with "https://storage.googleapis.com/...") within a React component, but finding the documentation unclear. Even after successful file upload, I keep receiving "ASSEMBL ...

Encountering unidentified data leading to the error message "Query data must be defined"

Currently, I'm utilizing Next.js to develop a project for my portfolio. In order to manage the API, I decided to implement both Tanstack query and Axios. The issue arises when attempting to retrieve the data as an error surfaces. Oddly enough, while ...

I am currently facing a challenge in React Highcharts where I am unable to remove and redraw the graph easily

Having an issue where I can't remove and redraw the chart in my React Highchart project. I've been unable to find a solution for this problem. Here is the code snippet: import { useState, useEffect, useRef } from "react"; import Highch ...

Will my NextJS 13 project remain server-side if I incorporate Redux?

I am looking to implement Redux in my NextJS 13 project with a specific folder structure. However, in order to do so, I need to use a provider which will be located in layout.jsx file. The provider requires the use of "use client" annotation to make it a c ...

Restrict users to submitting only one review per journal in Mongoose platform

I am currently working with three schemas: const journalSchema = new mongoose.Schema({ title: String, category: String, subcategory: String, review: [{type: mongoose.Schema.Types.ObjectId, ref: 'Review'}], link: String, description: S ...

Navigating multiple databases while managing a single model in Mongoose

I am looking to create a system with 50 arbitrary databases, each containing the same collections but different data. I want to use a single Node.js web application built with ExpressJS and Mongoose. Here is a simplified example: In this scenario: The ...

Avoiding the deployment of the test folder to the production environment within a node express application

Currently in the process of constructing a node express app, I have encountered a dilemma when shipping package.json to production. The issue lies in the fact that it includes code for unit testing as well. Is it advisable to create two separate package. ...

Leveraging Next.js to interact with secondary backend services while passing a JWT token through server actions

I'm currently facing an issue where I am working with Nextjs and NextAuth, and I need to access another backend by setting the Bearer token in the Authorization header. My concern is not exposing the token to the client, so I aim to retrieve it in a s ...

When Index.html is hosted via Express, the component fails to render

Following a tutorial has led me to the end and I've made changes to my App.js as shown below: import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <p>lm ...

VSCode is experiencing issues with recognizing .env* files for markup purposes and is also failing to recognize .env.local.* files

Current Environment: Utilizing NextJs, React, and VsCode Noticing a problem with syntax highlighting in my VSCODE editor. I have installed the following extensions: ENV DotEnv As per suggestions, I updated my json configuration file as follows: " ...

Sailsjs middleware that handles parsing of res.body data

I am a newcomer to JavaScript and recently started working with the sails framework. In my middleware, I am attempting to parse the HTTP response body to add a job to the celery queue. Despite following the documentation for skipper-, I continue to encount ...

Is it necessary to check the IP address along with the signature for Stripe webhook security?

My Next.js app utilizes webhooks to manage incoming customer payment events from Stripe. Following the provided example, my webhook first verifies the signature of the incoming event: const webhookSecret = process.env.SECRET_STRIPE_WEBHOOK const webhookHa ...