我有一个节点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的输出。
有人可以帮忙吗?