How to assign a json object in a particular localhost route to a variable in javascript

Viewed 137

I am quite new to learning web development and have been stuck for hours and my knowledge of Javascript is not that well. I have a route localhost:8080/api/employee/ so that when I enter this route in my browser it shows a JSON

[
    {
        "id":1,
        "employee_name":"Anders",
        "department_id":4
    },
    { 
        "id":3,
        "employee_name":"Brownea",
        "department_id":17
    },
    {
        "id":4,
        "employee_name":"Chow",
        "department_id":19
    }
]

In the more specific route, localhost:8080/api/employee/{id}, it shows for instance id: 1

{data: 
    {
        "id":1,
        "employee_name":"Anders",
        "department_id":4
    }
}

I am trying to assign a json object in a particular localhost route to a variable in javascript.

Currently the problem is the number 3

  1. In the javascript, I have tried this:

const fileHandler = async () => {
    const res = await fetch("localhost:8080/api/employee/1")
    .then((res) => {
        console.log(res)
    }
}

In the console it display:

XHRGEThttp://localhost:8080/api/employee/1
CORS Missing Allow Origin

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/employee/1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. EmployeeRegis.js:34
  1. I then try to do this in the javascript:

const res = await fetch("localhost:8080/api/employee/1", {
    method: "GET",
    mode: "no-cors",
})
.then((res) => {
    console.log(res)
}

The console shows:

XHRGEThttp://localhost:8080/api/employee/1
[HTTP/1.1 404 Not Found 7ms]

Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }
EmployeeRegis.js:34
  1. I also try the mm107 answer and do this:

const res = await fetch("http://localhost:8080/api/employee/1", {
    method: "GET",
    mode: "no-cors",
}).then(res => {
    console.log(res)
    console.log(res.json())
    res.json()
}).then(data => {
    console.log(data)
})

It still return some error in console:

Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }
EmployeeRegis.js:37

Promise { <state>: "pending" }
<state>: "rejected"
<reason>: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
​​columnNumber: 0
fileName: ""
lineNumber: 0
message: "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"
stack: ""
<prototype>: SyntaxError.prototype { stack: "", … }
<prototype>: Promise.prototype { … }
EmployeeRegis.js:39

undefined EmployeeRegis.js:43

Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data 2

I am using Golang as the backend, here is the handler (using GoFiber and gorm):

func HandlerEmployeeID(ctx *fiber.Ctx) error {
    employeeID := ctx.Params("id")

    var emply entity.Employee

    error := database.DB.First(&emply, "id = ?", employeeID).Error
    if error != nil {
        return ctx.Status(404).JSON(fiber.Map{
            "message": "failed get employee by the id",
        })
    }
    // Previously in number 1 and 2, I pathetically return 404 status not found
    // return ctx.Status(404).JSON(fiber.Map{
    //  "message": "successfully get employee by the id",
    //  "data":    emply,
    // })
    
    // In the number 3, I have update it like this
    return ctx.JSON(fiber.Map{
        "message": "successfully get employee by the id",
        "data":    emply,
    })
}

What I want on console.log(resSomething) returns this:

{data: 
    {
        "id":1,
        "employee_name":"Anders",
        "department_id":4
    }
}

How to do that?


Updated:

I just know that the mode: "no-cors" will not result in my expected response body. But, if I am not using that mode, it will keep returning an error in the console. I have tried to run parallelly lcp --proxyUrl http://localhost:8080/api/employee/1 but the CORS issue is still not handled.

2 Answers

You have to parse the response to JSON:

const res = await fetch("localhost:8080/api/employee/1", {
    method: "GET",
    mode: "no-cors",
})
.then(res => res.json())
.then(data => console.log(data))

And for the 404, it's probably some problem in the backend.

Allow

Options Method to work in your backend

Ensure your backend allows APIs to be called from another localhost.

The answer in first comment

    const res = await fetch("localhost:8080/api/employee/1", {
    method: "GET",
    mode: "no-cors",
})
.then(res => res.json())
.then(data => console.log(data))

Is one part of the problem.

Related