浏览器发送了两个请求,但只有本地主机被调用

时间:2018-07-25 14:56:25

标签: javascript node.js rest api

我有一个节点js API。

app.post('/myapi', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Request-With");
    res.header("Content-Type", "application/json");
    res.header("Accept", "application/json");
    * do something *
    res.json({ api : "api called successfully" });
});

我在公共文件夹中放置了一个html代码。我正在使用express来运行html代码和后端API。 我的html代码已将请求提取为,

var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json, text/plain, */*');

var options = {
  method: 'POST',
  body: JSON.stringify(loginDetails),
  headers: headers,
  mode: 'no-cors'
};
fetch('http://localhost:3001/myapi', options)
.then(function (response) {
  console.log(response);
  res=response.statusCode;
  // return response
  if (res==0) {
    window.location.assign("http://localhost:3001/home.html");
  }

});

当我在浏览器中运行代码时。当我单击调用上述前端代码的按钮时。它发送两个请求。两次呼叫均失败。一种是本地主机请求,即文档调用,另一种是API调用。但是API调用中没有任何响应。

我正在从/调用中获得UI响应,

cannot POST/

所以我尝试添加以下代码,

app.post('/', function (req, res) {
    res.json({ "status": "successfull" });
});

现在也有两个调用,但是UI返回{status:successl}(/的输出)。但它不会返回/ myapi的输出。

有人可以帮忙吗?

我正在获取本地主机文件的无限启动器。查看屏幕截图。 enter image description here

1 个答案:

答案 0 :(得分:0)

为请求添加任何唯一参数,以避免发送请求的缓存版本。

/api/name?id=<unique_param>

您可以找到更多详细信息herehere