Javascript 无法使用fetch从服务器获取相关数据
我有一个nodejs服务器,提供字典信息和关键字。例如,如果我键入'priced',当我转到URL:时,会得到JSON文本。 {“名字”:“昂贵”,“意思”:“花费很多钱”,“例子”:[“一瓶昂贵的酒”,“养一匹马很贵”]}。这在《邮递员》中也适用 我有一个单独的前端项目,它必须调用上面的URL{keyword},以便在转到时获得JSON。但是,我仍然无法使用fetch。下面是代码。请让我知道我错在哪里(我在Chrome控制台中没有得到任何错误,但也没有得到JSON文本):Javascript 无法使用fetch从服务器获取相关数据,javascript,node.js,reactjs,Javascript,Node.js,Reactjs,我有一个nodejs服务器,提供字典信息和关键字。例如,如果我键入'priced',当我转到URL:时,会得到JSON文本。 {“名字”:“昂贵”,“意思”:“花费很多钱”,“例子”:[“一瓶昂贵的酒”,“养一匹马很贵”]}。这在《邮递员》中也适用 我有一个单独的前端项目,它必须调用上面的URL{keyword},以便在转到时获得JSON。但是,我仍然无法使用fetch。下面是代码。请让我知道我错在哪里(我在Chrome控制台中没有得到任何错误,但也没有得到JSON文本): replyWith功
replyWith功能用于模拟响应。如果您想要合法的响应,请尝试以下操作:
let req = 'Dictionary app';
let resp;
fetch(url, {
method: 'POST',
body: req,
headers:{
'Content-Type': 'text/plain' //Be careful this is format for what you are sending not what you are receiving
}
}).then((res) => res.json())
.then((data) => {resp = data;}) //Store the data
.catch((error) => {console.error('Error:', error)})
我认为标题应该是:
'Content-Type':'application/json'
(或者'text/plain'
,如果您不使用json)是否将服务器配置为:7000以允许CORS请求?另请参阅
let req = 'Dictionary app';
let resp;
fetch(url, {
method: 'POST',
body: req,
headers:{
'Content-Type': 'text/plain' //Be careful this is format for what you are sending not what you are receiving
}
}).then((res) => res.json())
.then((data) => {resp = data;}) //Store the data
.catch((error) => {console.error('Error:', error)})