我只是想让这件事简短些。希望它不是那么简短,没有任何意义。我需要从API中读取标识符列表,这些标识符将用于随后“获取”与列表中的键相关联的JSON文件。列表数组存储在同一个端点的另一个JSON文件中,标识符为“keys.json”,为了防止该列表被处理两次,我想在检索它时立即将一个空数组写回'keys.json‘。
下面是“获取”列表的成功函数。
const getJsonKeys = async () => {
const options = {
method: 'GET',
uri: baseURL + keysID,
headers: { 'User-Agent': 'Request-Promise' },
json: true // Automatically parses the JSON string in the response
};
return (await rpn(options)).keys;
};
下面是我试图用的不成功的“帖子”:
const postEmptyJsonKeys = async () => {
const options = {
method: 'POST',
uri: baseURL + keysID,
body: {
keys: []
},
json: true // Automatically stringifies the body to JSON
};
return (await rpn(options)).req.Request.body;
};
下面是调用它们的块:
module.exports = (rtProcess) => {
rtProcess.get('/process', async (req, res, next) => {
const jsonKeysList = await (getJsonKeys());
console.log("Retrieved Keys", jsonKeysList);
try {
const req = await (postEmptyJsonKeys());
console.log("Wrote", req.Request.body);
} catch(err) {
console.log(err.statusCode, err.error);
console.log(err);
}
//
// more code here
//
jsonKeysList.forEach(courseID => {
//
// more code here
//
});
res.render("process");
}); // end of process route
}; // end of module exports
我已经尝试了我所知道的一切,在周围的各种文档中找出答案,但我找不到任何东西告诉我为什么会使用catch块,而只能成功地尝试一下。
顺便说一下,error.status代码是404。
这个错误是一个看起来像HTML的字符串,这对我来说也是一个谜,因为我试图发布一个简单的:
{
keys: []
}
发布于 2018-11-08 12:27:40
所以这个错误:
Cannot POST /static/quizdata/keys.json
这让我认为您要访问的POSTing端点没有被正确定义,这就是为什么您得到一个404
--它告诉您没有匹配该请求的POST
处理程序。
由于问题是node.js
标记,我可以在URL中看到static
部分,这使我认为您可能正在使用内置中间件为静态内容服务,如果是这样的话,那么这就是为什么您不能在那里提供任何东西,因为中间件不是用于这个目的的,它只会处理GET
请求。
对于您的评论,它不是静态内容,因为路由中包含static
,或者因为它位于一个名为static
的目录中(如果是这样的话)。
看一下下面的例子:
GET
请求,如http.../static/path/inside/public/dir.png
:
App.use(‘/静态’,express.static('public'));GET
请求,如http.../assets/path/inside/public/dir.png
:
App.use(‘/资产’,express.static('public'));GET
请求,如http.../whatever/something/inside/public/dir.png
:
App.use(‘/什么’,express.static('public'));GET
请求,如http.../something/inside/public/dir.png
:
app.use(express.static('public'));GET
请求,如http.../something/inside/my-static-files/dir.png
:
App.use(express.static(‘my-static’));您可以在官方文件中找到更多的示例。
无论如何,让我们假设您正在使用此选项提供静态内容:
app.use('/static', express.static('public'));
您还可以添加另一个中间件来处理POST
请求。就像这样:
const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;
...
app.post('/static', (req, res, next) => {
// Just an example, you can replace the path and the []
// with anything you want:
fs.writeFileSync('path/to/file.json', JSON.stringify([]));
});
app.use('/static', express.static('public'));
app.listen(port, () => console.log(`Listening on port ${port}!`));
您可能还会发现另一个有用的问题:在Express应用程序中从JS文件中追加JSON文件
https://stackoverflow.com/questions/53164982
复制相似问题