问题描述
我正在使用此代码获取用户输入,将其处理为可用格式,然后将其发布到 Node Express 服务器。当 write 函数被调用时,数据是“未定义的”?
当我在浏览器中将此代码作为文件打开时,它工作正常,除了 fetch 帖子,因为我使用的是 Node-fetch。
我还使用 browserify/watchify 将 Node-fetch 与我的代码捆绑在一起,这似乎是问题所在。当我将提取移动到处理输入的同一个函数中时,它工作正常。
出于某种原因,browserify 没有将数据发送到写入函数。
我真的希望将服务器通信与客户端数据处理分开。
有什么建议吗?
function add_cat() {
let name = document.getElementById("name").value;
const nodePros = document.querySelectorAll('input.pro');
const nodeCons = document.querySelectorAll('input.con');
let stringPros = [];
let stringCons = [];
nodePros.forEach(currentValue => {
let pro = currentValue.value.toString();
if (pro.length > 0) {
stringPros.push(pro);
}
});
nodeCons.forEach(curValue => {
let con = curValue.value.toString();
if (con.length > 0) {
stringCons.push(con);
}
});
write_cat(name,stringPros,stringCons);
}
module.exports = add_cat;
function write_cat(name,stringCons) {
const fetch = require('node-fetch');
(async() => {
const rawResponse = await fetch('http://localhost:8080/api/categories?',{
method: 'POST',headers: {
'Accept': 'application/json','Content-Type': 'application/json'
},body: JSON.stringify({
name: name,pros: stringPros,cons: stringCons
})
})
const content = await rawResponse.json();
console.log(content);
})();
}
module.exports = write_cat;
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)