Home > Blockchain >  Next Js API not posting to an external API
Next Js API not posting to an external API

Time:12-21

so i was trying to make 2 different projects first one is my ecommerce frontend made with next js and second one is ecommerce dashboard which is also made with next js. But when i am trying to post products from my dashboard to my ecommerce frontend nothing is happening even also I am not getting any error in console that's why i am unable to understand what is the problem. Can anyone help me in this ? The fetch code is below.

const handelSubmit = async (e) => {
  e.preventDefault();
    console.log("clicked");
  
    fetch(`http://192.168.43.53:3000/api/products`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(
          name,
          price,
          // mediaUrl,
          description,
          collect,

        

      ),
    })
  };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

CodePudding user response:

Nextjs apis only work with the same origin by default, see Nextjs api Caveats for more info.

If you want to make a fully public api with Nextjs, you have to add cors, see Api Middlewares. Your code will look something like:

import Cors from 'cors'

// Initializing the cors middleware
const cors = Cors({
  methods: ['GET', 'HEAD'],
})

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result)
      }

      return resolve(result)
    })
  })
}

If your backend api isn't defined with Nextjs, please share the code of your requested api endpoint and also the technology it uses.

CodePudding user response:

I think the data you are posting needs to be in JSON first.

body: JSON.stringify(
          key:value,
          key1:value1
        )
  • Related