-1

I can hit this endpoint http://localhost:8000/api/signup via Postman and it returns JSON

POST http://localhost:8000/api/signup

{
    "name": "Username",
    "email": "username@mail.co",
    "password": "abcedf"
}

The response

{
    "message": "Signup success! Please signin"
}

In my frontend (built with next.js) I am trying to use fetch to do the same thing, but I get 3 errors:

GET http://localhost:8000/api/signup net::ERR_ABORTED 404 (Not Found)

SyntaxError: Unexpected end of input at eval (auth.js?8ae0:18) "error"

Uncaught (in promise) TypeError: Cannot read property 'error' of undefined

config.js

import getConfig from 'next/config'

const { publicRuntimeConfig } = getConfig()

export const API = publicRuntimeConfig.PROD ? 'https://production.website.com' : 'http://localhost:8000'
export const APP_NAME = publicRuntimeConfig.APP_NAME

auth.js

import fetch from 'isomorphic-fetch'
import { API } from '../config'

export const signup = user => {
    // return fetch(`${API}/signup`,
    return fetch(`http://localhost:8000/api/signup`,
        { mode: 'no-cors'},
        {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify(user)
    })
        .then(res => {
            return res.json()
        })
        // .then(data => console.log('success:', data))
        .catch(err => console.log(err, 'error'))
}

The submit function from SignupComponent.js

const handleSumbit = e => {
    e.preventDefault()
    // console.table({ name, email, password, error, loading, message, showForm })
    setValues({...values, loading: true, error: false})
    const user = { name, email, password }

    signup(user)
    .then(data => {
        if(data.error) {
            setValues({ ...values, error: data.error, loading: false })
        } else {
            setValues({...values, name: '', email: '', password: '', error: '', loading: false, message: data.message, showForm: false})
        }
    })
}

Backend Server Console each time I trigger handleSubmit

GET /api/signup 404 0.417 ms - 149
GET /api/signup 404 0.516 ms - 149
GET /api/signup 404 0.499 ms - 149
GET /api/signup 404 0.313 ms - 149

What am I missing?

Dabolo
  • 9
  • 6
  • 1
    It returns `"JSON"`, or it returns a properly formatted JSON string? `Unexpected end of input` sounds like `res.json()` failed to parse the data. Try `res.text()` if it's not real JSON. If not, can you show us what the result you get in Postman looks like? – blex Jul 07 '20 at 00:16
  • I tried `res.text()` because I had an error `"SyntaxError: Unexpected token < in JSON at position 0 "error" "` meaning it returns `html` instead of Json. Here is the Json from Postman: https://i.imgur.com/B9S0nyx.png – Dabolo Jul 07 '20 at 15:51

2 Answers2

0

I think it is because of your statements

 .then(res => {
            return res.json()
        })

you are returning a promise using fetch, you should .then() and .catch() where the function returns not within the function itself

signup(user)
    .then(data => {
     do something with data      
})
.catch((err) => handle err))
export const signup = user => {
    // return fetch(`${API}/signup`,
    return fetch(`http://localhost:8000/api/signup`,
        { mode: 'no-cors'},
        {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify(user)
    })

this should be the end of this function

d0rf47
  • 409
  • 8
  • 20
  • Thank you for the informations. However my console still showing me some errors. I think that my API don't want to connect with the front. `Failed to load resource: the server responded with a status of 404 (Not Found)`. Tried with full address `http://localhost:8000/api/signup` and `${API}/signup`. – Dabolo Jul 07 '20 at 22:57
  • If anyone is having issues related to CORS, please refer to this conversation: https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – noob_nerd Dec 28 '20 at 13:09
0

If it is a Signup route the error should start with POST not GET. As you are receiving the error as GET http://localhost:8000/api/signup net::ERR_ABORTED 404 (Not Found) Please check your routes seems that your router and controller is mismatched methods