如何将特定localhost路由中的json对象分配给javascript中的变量



我对学习web开发很陌生,已经被困了几个小时,我的Javascript知识不是那么好。我有一个路由localhost:8080/api/employee/当我在浏览器中输入这个路由时它会显示一个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
}
]

在更具体的路由localhost:8080/api/employee/{id}中,它显示例如id: 1

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

我试图在特定的本地主机路由中分配json对象到javascript中的变量。

目前的问题是数字3

  1. 在javascript中,我尝试了这个:

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

在控制台中显示:

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. 然后我尝试在javascript中这样做:

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

控制台显示:

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. 我也尝试mm107的答案,并这样做:

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)
})

控制台仍然返回一些错误:

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

我使用Golang作为后端,这里是处理程序(使用GoFibergorm):

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,
})
}

我想要的console.log(resSomething)返回这个:

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

怎么做?


更新:

我只知道mode: "no-cors"不会导致我预期的响应体。但是,如果我不使用那个模式,它会一直在控制台中返回一个错误。我已经尝试并行运行lcp --proxyUrl http://localhost:8080/api/employee/1,但CORS问题仍然没有处理。

您必须将响应解析为JSON:

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

对于404,可能是后端有问题。

允许

Options在后台工作的方法

确保你的后端允许api从另一个本地主机调用。

第一条注释中的答案

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

是问题的一部分。

相关内容

  • 没有找到相关文章

最新更新