javascript - RESTful API 请求
问题描述
首先,我是巴西人,只是提醒您注意我可能犯的任何英语错误
我正在尝试通过 HTTP 为 RESTful API 发送请求,但我没有收到任何响应
<html>
<head>
<title>BUSAO</title>
<button type="submit" onclick="get()">GET</button>
<button type="submit" onclick="post()">POST</button>
<script type="text/javascript" language="javascript">
function get() {
const userAction = async() => {
const response = await fetch('http://scristovao.azurewebsites.net/api/LastPositions', {
method: 'GET',
headers: {
'Authorization': 'Bearer <>',
'Access-Control-Allow-Origin': '*'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
console.log(myJson)
}
}
function post() {
const userAction = async() => {
const response = await fetch('http://scristovao.azurewebsites.net/api/Login', {
method: 'POST',
body: {
'UserID': '<>',
'Password': '<>'
}, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
console.log(myJson)
}
}
</script>
</head>
<body marginheight="0" marginwidth="0">
<IMG NAME="imgBanner" WIDTH="100%" HEIGHT="100%" BORDER="0" cellspacing="0" cellpadding="0">
</body>
</html>
解决方案
您的 get() 和 post() 永远不会调用 API。
您的函数创建了一个从未调用过的新函数。
function get() {
const userAction = async() => {} // This creates a new async function, which is not invoked
你甚至可以自己测试!
function get() {
const userAction = async() => {
console.log('do get') // Never gets logged when calling get()
}
所以让我们删除函数包装
async function get() {
console.log('do get') // Now get logged when calling get()
const response = await fetch('http://scristovao.azurewebsites.net/api/LastPositions', {
method: 'GET',
headers: {
'Authorization': 'Bearer <BEARER_TOKEN>',
'Access-Control-Allow-Origin': '*'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
console.log(myJson)
return myJson
}
你的帖子功能是一样的。去掉包装后:
async function post() {
const response = await fetch('http://scristovao.azurewebsites.net/api/Login', {
method: 'POST',
body: {
'UserID': '<username>',
'Password': '<password>'
}, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
console.log(myJson)
return myJson
}
推荐阅读
- android - 布局中的正确管理按钮 - Android Studio
- angular - 关键依赖:依赖的请求是一个表达式 - Angular SSR
- excel - 将范围从 excel 表保存到文本文件
- docker - 无法在 docker 容器中连接到我的代理
- c# - Unity Animator 不显示现在处于活动状态的动画
- c# - C# 在 2 个数组之间更改值
- r - 使用 str_to_title 更改 col 名称时出现问题
- node.js - 无法使用 node.js AWS Lambda 函数使用“ftp”包连接到 ftp 服务器
- excel - 将多个 Excel 文件中的数据复制到一个主工作簿中。但是,应使用 powershell 脚本以明智的方式添加数据
- c - C:警告:不兼容的指针类型将“int **”传递给“int *”类型的参数