JavaScript Ajax无法正常运行

时间:2018-06-19 16:12:14

标签: javascript ajax

我正在用JavaScript编写一个自定义HTTP客户端,我的代码对我来说似乎还可以,但是它将继续获得404的请求。我已经在具有此处理程序的NodeJS(ExpressJS)服务器上运行此程序。

app.post('/api/update', (req, res) => {
    res.send(req.body);
});

这是我的js代码

const HTTPClient = (method, url, post) => {
  return new Promise((resolve, reject) => {

    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);

    xhr.onload = () => {
      const statusText = xhr.statusText || '';

      // responseText is the old-school way of retrieving response (supported by IE9)
      // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
      const response = ('response' in xhr) ? xhr.response : xhr.responseText;

      // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
      let status = xhr.status === 1223 ? 204 : xhr.status;

      // fix status code when it is 0 (0 status is undocumented).
      // Occurs when accessing file resources or on Android 4.1 stock browser
      // while retrieving files from application cache.
      if (status === 0) {
        status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
      }
      try {
        return resolve(JSON.parse(response));
      } catch (error) {
        return resolve(response);
      }
    };

    xhr.onerror = () => reject('Error');
    xhr.ontimeout = () => reject('Timeout');
    xhr.onabort = () => reject('Abort');

    xhr.send(JSON.stringify(post) || null);
  });
};


HTTPClient('post', '/api/update', defaultData).then(response => {
  css.value = response.data;
  console.log(response);
}, error => {
  console.error(error);
});

注意:defaultData是和对象

1 个答案:

答案 0 :(得分:0)

您忘记添加Content-type标头。

const HTTPClient = (method, url, post) => {
  return new Promise((resolve, reject) => {

    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);

    // UPDATE
    xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

    xhr.onload = () => {
      const statusText = xhr.statusText || '';

      // responseText is the old-school way of retrieving response (supported by IE9)
      // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
      const response = ('response' in xhr) ? xhr.response : xhr.responseText;

      // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
      let status = xhr.status === 1223 ? 204 : xhr.status;

      // fix status code when it is 0 (0 status is undocumented).
      // Occurs when accessing file resources or on Android 4.1 stock browser
      // while retrieving files from application cache.
      if (status === 0) {
        status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
      }
      try {
        return resolve(JSON.parse(response));
      } catch (error) {
        return resolve(response);
      }
    };

    xhr.onerror = () => reject('Error');
    xhr.ontimeout = () => reject('Timeout');
    xhr.onabort = () => reject('Abort');

    xhr.send(JSON.stringify(post) || null);
  });
};


HTTPClient('post', '/api/update', defaultData).then(response => {
  css.value = response.data;
  console.log(response);
}, error => {
  console.error(error);
});