首页 > 解决方案 > 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是和对象

标签: javascriptajax

解决方案


您忘记添加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);
});

推荐阅读