Fetch API post永远不会落入.then

Fetch API post never falling into .then

本文关键字:then API post 永远 Fetch      更新时间:2023-09-26

这是我的代码,它的工作是发布数据,但"。那么"部分"就不会被触发。如何触发"。then"?这是它唯一一次落入"。然后"是当我提交时,当表单为空。

HTML:

<form>
                <input name="username" class="no-top input" type="text" placeholder="username"></input>
                <input name="password" class="input" type="password" placeholder="password"></input>
                <div class="table">
                    <div class="table-row">
                      <div class="table-cell">
                        <button class="button" type="submit" value="Login" onclick="post.account.login()"></button>
                      </div>
                      <div class="table-cell">
                        <div class="box">Forgot password?</div>
                        <div class="box">Request access</div>
                      </div>
                    </div>
                </div>
              </form>
JAVASCRIPT:

const request = new Request('http://localhost:8000/account/access', {
        method: 'POST',
        headers: header,
        redirect: 'manual'
        body: JSON.stringify({
          email_address: document.getElementsByName('email_address')[0].value,
          created_date: now()
        })
      })
  fetch(request).then((response) => {
    alert('test')
    if (response.status >= 400) throw new Error("Bad response from server")
    if (response.status == 200)
      return response.json()
  }).then((response) => {
    console.log('success')
  })

试试这个…

  var myRequest = new Request('demo.php', {method: 'POST', body: '{"foo":"bar"}'});
  fetch(myRequest)
.then(function(response) {
    if(response.status == 200) //return response.json();
    console.log(response);
    else console.log('Something went wrong on api server!');
})
 .catch(function(error) {
    console.error(error);
});

如果像这样在。then链中添加。catch

const request = new Request('http://localhost:8000/account/access', {
    method: 'POST',
    headers: header,
    redirect: 'manual'
    body: JSON.stringify({
        email_address: document.getElementsByName('email_address')[0].value,
        created_date: now()
    })
})
fetch(request).then((response) => {
    alert('test')
    if (response.status >= 400) throw new Error("Bad response from server")
    if (response.status == 200)
        return response.json()
}).then((response) => {
    console.log('success')
}).catch(function(err) {
    console.log(err);
});

你会看到错误是什么

另外,看看你的浏览器开发工具控制台-我敢打赌你会看到一些关于CORS的错误