Douglas
Douglas

Reputation: 381

POST request not returning Allow-Origin header

I'm trying to make a POST request on a AWS lambda that has cors enabled and I using the cors package in the API. Then I make a POST request with fetch but I get this error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

The cors package was not supposed to take tare of this or I need to do some additional configuration?

api.js

import { json, urlencoded } from 'body-parser'
import express from 'express'
import cors from 'cors'

import recipe from './routes/recipe'
import login from './routes/login'
import unit from './routes/unit'

const app = express()

app.use(cors()) // enabling cors
app.use(json())
app.use(urlencoded({ extended: true }))

app.use('/recipes', recipe)
app.use('/login', login)
app.use('/units', unit)

request.js

const params = { 'POST', body, mode: 'cors' }
return await (await fetch(baseURL + endpoint, params)).json()

recipe.js

import { Router } from 'express'
const router = Router()

router.post('/', async ({ body }, res) => {
  // save recipe in database
  res.json(recipeId)
})

export default router

full source code - api: https://github.com/EliasBrothers/zanzas-recipes-api/tree/beta-develop frontend - https://github.com/EliasBrothers/zanzas-recipes-web/tree/develop

Upvotes: 0

Views: 224

Answers (2)

Douglas
Douglas

Reputation: 381

I made it work by updating the packages from the project and changing the request

 const stringifiedBody = JSON.stringify(body) // added
  const params = {
    method,
    body: stringifiedBody,
    mode: 'cors',
    headers: { // added
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  }

Upvotes: 1

Kevin Law
Kevin Law

Reputation: 852

I'm not sure if this is a copying error, you didn't specify the fetch method POST in right way. Sometimes a Not Found page will also be recognized as CORS problem. Have you tried to normalize your fetch parameters?

params = {
 method: 'POST',
 body: body,
 mode:'cors'
}

Upvotes: 0

Related Questions