The Next.js API endpoint is struggling to process cross-domain POST requests

Dealing with a POST request in my NextJS application has been challenging. This particular post request is originating from a different domain.

To address this issue, I included a receptor.ts file in the /pages/api directory:

import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    console.log('POST')
    const message = req.body.message;
    console.log(`Message: ${message}`);
    res.status(200).json({ message: "Ok" });
  } else {
    res.status(405).json({ error: "Not allowed" });
  }

  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST');
}

And here is how it's being utilized from the other app:

const url = `http://localhost:3000/api/receptor`;
            const data = { message: "Hello" };

            fetch(url, {
              method: "POST",
              headers: {"Content-Type": "application/json"},
              body: JSON.stringify(data)
            })
              .then(response => response.json())
              .then(data => console.log(data))
              .catch(error => console.error(error));

The following error appears in the browser's console:

Access to fetch at 'http://localhost:3000/api/receptor' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Additionally, the IDE's console shows:

error - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I have tried adding mode: "no-cors" to the request, but encountered the same errors. Any advice on resolving this situation?

SOLUTION

import { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') {
    res.status(200).end();
    return;
  }

  if (req.method === 'POST') {
    console.log('POST')
    const message = req.body.message;
    console.log(`Message: ${message}`);
    res.status(200).json({ message: "Ok" });
  } else {
    res.status(405).json({ error: "Not allowed" });
  }
}

The underlying issue was not addressing the preflight request. The provided solution resolves this, and I will recommend closing the matter.

Answer №1

The API endpoint you have created is not correctly handling the OPTIONS request method. It is important to ensure that it properly responds to OPTIONS requests and includes the necessary Access-Control-* headers. Additionally, you may need to include the header

Access-Control-Allow-Headers: Content-Type
.

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

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

Verify the status of the mongodb server synchronously

Is there a method to detect if a mongod instance is still operational while using mongoclient? In my mongoclient module, I have implemented a db.on('close') handler which functions properly when mongod exits normally. However, if the server proc ...

Using Javascript to make a call to a RESTful endpoint

My current challenge involves attempting to make a call to the Spotify API from JavaScript: function callAPI() { var xhttp = new XMLHttpRequest(); xhttp.open('GET', 'https://api.spotify.com/v1/search?q=Muse&type=track'); ...

What is the best way to conceal the legend in a chart.js component within a React application?

I've been struggling to hide the legend on my Chart.js chart. Per the official documentation (), hiding the legend requires setting the display property of the options.legend object to false. I attempted the following approach: const options = { ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

Having difficulty accessing information from Firebase database using the .once() function

When a button is clicked on the page, I need to fetch data from a Firebase database using the once() function. Despite setting up the necessary references and variables, the data retrieval seems to be unsuccessful as the global variable numElections keeps ...

Show me a way to use jQuery to show the number of images of a particular type that are on a

My webpage features 6 different images, including 4 of various balls such as basketball and baseball. One image is of a truck, while the last one is random. On the page, there is a form with two radio buttons allowing users to select which type of image c ...

Guide on implementing a looping settimeout function on a sliding page to dynamically load an HTML template within the Framework 7 framework

My current setup involves using Framework7 (framework7.io). The code below functions correctly on the main view page, utilizing a looping settimeout to refresh signups.html every second: <script type=“text/javascript” src=“code.jquery.com/jquery- ...

Why isn't cancelAll function available within the onComplete callback of Fine Uploader?

This is the completion of my task. $('#fine-uploader-house').fineUploader({ ... }).on('complete', function(event, id, name, jsonData) { if(!checkEmpty(jsonData.cancelAll) && jsonData.cancelAll){ //$(this).cancelAll(); ...

Error encountered in Three.js when using multiple canvases and loading JSON geometry

I have been working on creating multiple views and came across an example code here which worked flawlessly when I tried it. However, when I replaced the geometries with ones I created in Blender, I encountered an error: Cannot read property 'length ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Setting up Splide.js Auto Scroll Carousel in Next.js 13: A Comprehensive Guide

Having some trouble integrating Splide.js, a versatile and responsive carousel library, into my Next.js 13 project. Despite following the documentation and experimenting with different methods, I'm struggling to set it up correctly. Can anyone offer a ...

Unlock the power of Angular JS to display dynamic content effortlessly

My experience with AngularJs is very limited. In one of my projects, I need to display dynamic content on a page that changes based on the database values retrieved via an HTTP GET request. Before implementing the entire functionality, I decided to test i ...

Sending a second request with jQuery to upload a file

After successfully uploading a file using jQuery AJAX along with a progress bar (XHR), the next step involves processing the uploaded file on the server side. To check the status of this server-side processing, I attempt to make another jQuery AJAX request ...

Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information: var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start&ap ...

When using Selenium async script in its own thread, it can interrupt the execution of other

Let's consider this situation: Various scripts need to run in the browser. One of them involves sending messages from one browser to another (WebRTC). I am interested in measuring the delay for each operation, especially when it comes to sending mess ...

What is the best way to adjust the height of an IFrame to match the size of its content?

I attempted to set the height of an IFrame to 100% (similar to setting a <div> to height:auto). I specified the height attribute in the <iframe> tag as 100% and also set the height in the style to 100%, but it doesn't appear to be functio ...

Issues with jQuery code functionality within web forms

After creating a jQuery script to alter the CSS of a table row, I tested it on JSFiddle and it worked perfectly. However, when implemented into my web project, it doesn't seem to be functioning as intended. See the code below: HTML: <script src ...

Converting a base64 string to a PNG format for uploading to an S3 bucket from the frontend

Feeling a bit overwhelmed here, hoping this isn't just a repeat issue. I've come across similar problems but none of the solutions seem to be working for me at the moment. I'm currently utilizing react-signature-canvas for allowing users to ...

Error: The value of 'id' cannot be assigned to an undefined property

Recently, I've been delving into learning JS Express and decided to create a basic solution to handle GET / DELETE / POST / PUT requests. Everything was running smoothly until I encountered an issue with the POST router. Below is the code snippet for ...