英文:
Can't fetch local API with JavaScript
问题
我用Go编写了一个CRUD API。我在Postman中成功调用了它,但是在JavaScript中使用fetch方法获取数据时,在控制台中出现了以下错误:
todo.js:14 GET https://10.0.154.123:8080/todos net::ERR_SSL_PROTOCOL_ERROR
(anonymous) @ todo.js:14
getData @ todo.js:13
(anonymous) @ todo.js:60
todo.js:14 Uncaught (in promise) TypeError: Failed to fetch
at todo.js:14:9
at new Promise (\<anonymous\>)
at getData (todo.js:13:12)
at todo.js:60:1
这是我的JavaScript中的getData
函数:
function getData(urlTail) {
let options = {
method: 'GET',
redirect: 'follow'
}
// console.log(OK)
return new Promise(function(resolve) {
fetch('http://10.0.154.123:8080/todos', options)
.then(response => response.json())
.then(response => {
resolve(response);
})
});
}
以及Go中的代码(使用gin框架):
func main() {
router := gin.Default()
router.GET("/todos", getTodos)
router.GET("/todo/:id", getTodo)
router.POST("/todo", addTodo)
router.DELETE("/todo/:id", removeTodo)
router.PUT("/todo/:id", updateTodo)
router.Run("10.0.154.123:8080")
}
我猜测这是因为它自动将协议更改为https,但我无法修复。希望能得到你的帮助。谢谢。
英文:
I coded a crud API by Go. I called it successfully by Postman, but I fetched it by JavaScript and got this error in console:
todo.js:14 GET https://10.0.154.123:8080/todos net::ERR_SSL_PROTOCOL_ERROR
(anonymous) @ todo.js:14
getData @ todo.js:13
(anonymous) @ todo.js:60
todo.js:14 Uncaught (in promise) TypeError: Failed to fetch
at todo.js:14:9
at new Promise (\<anonymous\>)
at getData (todo.js:13:12)
at todo.js:60:1
This is my getData
function in JS:
function getData(urlTail) {
let options = {
method: 'GET',
redirect: 'follow'
}
// console.log(OK)
return new Promise(function(resolve) {
fetch('http://10.0.154.123:8080/todos', options)
.then(response => response.json())
.then(response => {
resolve(response);
})
});
}
and code in Go (gin framework):
func main() {
router := gin.Default()
router.GET("/todos", getTodos)
router.GET("/todo/:id", getTodo)
router.POST("/todo", addTodo)
router.DELETE("/todo/:id", removeTodo)
router.PUT("/todo/:id", updateTodo)
router.Run("10.0.154.123:8080")
}
I guess this because it auto changed the protocol to https but I can't fix. Hope to have your help. Thank you.
答案1
得分: 2
尝试通过不安全的连接(HTTP)从通过安全连接(HTTPS)提供的网页中获取API时,存在安全连接(SSL)的问题。由于同源策略的限制,这是不可能的。要解决此问题,您应该在服务器和客户端之间使用相同的协议(HTTP或HTTPS)。
英文:
There is a problem with the secure connection (SSL) when trying to fetch an API through an insecure connection (HTTP) from a webpage served through a secure connection (HTTPS). It is not possible due to Same-origin Policy. To resolve this issue, you should use same protocol (either HTTP or HTTPS) for both server and client.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论