Fetch API帖子永远不会落入.then

时间:2016-10-21 04:48:47

标签: javascript fetch fetch-api

这是我的代码,用于发布数据但是" .then"部分未被触发。我怎样才能触发" .then"?唯一一次落入" .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')
  })

2 个答案:

答案 0 :(得分:0)

试试这个..

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

答案 1 :(得分:0)

如果您将.catch添加到.then链中,就像这样

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的错误