首先,我是巴西人,以提醒您我可能犯的任何英语错误
我正在尝试通过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>
答案 0 :(得分:3)
您的get()和post()将永远不会调用API。
您的函数会创建一个永远不会调用的新函数。
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
}
您的发布功能是相同的。除去包装后:
<v-app>
答案 1 :(得分:1)
根据我在您的代码段中看到的,是您在单击时调用一个函数,该函数不会返回任何内容,而只是将函数设置为变量。因此,要获得想要的行为,您应该将其更改为以下内容:
function get() {
const userAction = async() => {
const response = await fetch('http://scristovao.azurewebsites.net/api/LastPositions', ...);
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
console.log(response)
}
// call the action itself to start the fetch
userAction();
}
function post() {
const userAction = async() => {
const response = await fetch('http://scristovao.azurewebsites.net/api/Login', ...);
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
console.log(myJson)
}
// call the action itself to start the fetch
userAction();
}