简体   繁体   English

快速发布请求在 chrome 中超时

[英]Express post request timing out in chrome

I am new to API development and am trying to create a post request and send data to an API but it keeps timing out in chrome.我是 API 开发的新手,正在尝试创建发布请求并将数据发送到 API,但它在 chrome 中一直超时。 The error I am getting is net::ERR_EMPTY_RESPONSE.我得到的错误是 net::ERR_EMPTY_RESPONSE。 This is my js where I am trying to send the info.这是我试图发送信息的 js。 It is called in another method called addToCart() where I am passing in the cart as a parameter.它在另一个名为 addToCart() 的方法中调用,我将购物车作为参数传入。

function sendToAPI(cart) {
  var req = new XMLHttpRequest();
  req.open('POST', '/add');
  req.setRequestHeader('Content-Type', 'application/json');
  req.send(JSON.stringify({cart : cart}));
  req.addEventListener('load', () => {
    console.log(req.resonseText);
  })
  req.addEventListener('error', () => {
    console.log('There was an error');
    console.log(error);
  });

}

This is where I am creating the API:这是我创建 API 的地方:

const express = require("express");
const bodyParser = require("body-parser");

const api = express();

api.use(express.static(__dirname + '/public'));
api.use(bodyParser);

api.listen(3000, function() {
  console.log("Server is running on port 3000");
});


api.post('/add', function(req, res) {
  console.log(req.body);
  res.send("It works");
});

I see a couple problems.我看到了一些问题。 First, this is not correct:首先,这是不正确的:

api.use(bodyParser);

For a JSON response, you would do this:对于 JSON 响应,您可以这样做:

api.use(bodyParser.json());

And, body-parser is built into Express so you don't need to manually load the body-parser module.而且,body-parser 内置于 Express 中,因此您无需手动加载 body-parser 模块。 You can just do this:你可以这样做:

api.use(express.text());

Then, in your client-side code, this:然后,在您的客户端代码中,如下:

console.log(req.resonseText);

is misspelled and should be this:拼写错误,应该是这样的:

console.log(req.responseText);

And, in your client-side code, you should also be checking the status code returned by the response.而且,在您的客户端代码中,您还应该检查响应返回的状态代码。

FYI, the new fetch() interface in the browser is soooo much nicer to use than XMLHttpRequest .仅供参考,浏览器中新的fetch()接口比XMLHttpRequest好用得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM