请求挂起,处于挂起状态



我有以下内容:

app.post('/template-preview', (req, res) => {
console.log(`here is req: ${req}`);
res.send('it was hit');
res.render('main', {layout : 'index'});
});

然后我使用Axios拨打以下电话:

const getPreviewTemplate = async () => {
console.log('in get previewtemplate')
const result = await axios.post('http://localhost:5000/template-preview',
{firstName: 'frank', lastName: 'gomez'}
);
result.then(res => {
console.log(res);
})
return result;
}

我可以确认以下工作,因为我得到了console.log('ingetpreviewtemplate'(;然而,在那之后它就挂了。当我转到chrome中的网络选项卡时;挂起";请求。它一直是这样。

我有这个在我的快递代码中处理cors之前的路线。不确定这是否是问题的原因:app.use(cors);

我做错了什么?

这里有很多错误。很难确定是哪一个导致了您的问题,因为您除了";它挂起了";。

首先,getPreviewTemplate()根本没有错误处理。如果你的axios.post()拒绝,你没有记录它的代码。

其次,const result = await axios.post()返回的是实际结果,而不是承诺。所以,你不能在上面做result.then()

第三,这里的console.log(是req:${req}`(;won't help you because that will try to convert req to a string which will probably just be "[Object object]". Instead, you need to do:console.log('这里有req:',req(;so you pass the whole object toconsole.log((`并让它使用其显示智能来显示对象。

第四,app.use(cors);应该是app.use(cors());,这很可能就是为什么每个请求都被卡住的原因,因为next()从未被调用过。

第五,您只能为每个传入请求发送一个响应,因此尝试同时执行res.send()res.render()是错误的。选择其中一个,而不是两者都选。

总结:

更改此项:

app.use(cors)

到此:

app.use(cors());

更改此项:

app.post('/template-preview', (req, res) => {
console.log(`here is req: ${req}`);
res.send('it was hit');
res.render('main', {layout : 'index'});
});

到此:

app.post('/template-preview', (req, res) => {
console.log('here is req: ', req);
res.render('main', {layout : 'index'});
});

更改此项:

const getPreviewTemplate = async () => {
console.log('in get previewtemplate')
const result = await axios.post('http://localhost:5000/template-preview',
{firstName: 'frank', lastName: 'gomez'}
);
result.then(res => {
console.log(res);
})
return result;
}

到此:

const getPreviewTemplate = async () => {
console.log('in get previewtemplate')
const result = await axios.post(
'http://localhost:5000/template-preview',
{firstName: 'frank', lastName: 'gomez'}
);
console.log(result);
// this will be the resolved value of the promise
// that this async function returns
return result;
}

然后,无论谁调用getPreviewTemplate(),都将得到一个承诺,并且必须在他们得到的承诺上使用await.then()才能得到实际结果。

如果您没有正确解析json,这是非常常见的。请确保在您使用的服务器文件中。

server.use(express.json())

如果你已经有了这个,请确保它在正确的位置,因为它是自上而下读的,所以位置很重要。

最新更新