简体   繁体   English

在Node.js中使用Express成功后,如何发送JSON响应并重定向到某些html页面?

[英]How to send a JSON response and redirect to some html page after success in Node.js using express?

I am trying to send a JSON response, and redirect the page at the same time. 我正在尝试发送JSON响应,并同时重定向页面。 It is not happening. 这没有发生。 Is there any way to redirect in Express.js while sending some JSON response to client? 向客户端发送一些JSON响应时,是否可以在Express.js中进行重定向? I want to use this JSON response to render the value to the redirected HTML page. 我想使用此JSON响应将值呈现到重定向的HTML页面。

My Code - 我的代码-

//I tried using the below code. But it is not working
const app = express();

app.get('/user', authenticationMiddleware, (req,res) => {

    res.send({name : "StackOverFlow", reason : "Need help!"});

    res.redirect('/user/me');

})

Expected result : 预期结果 :

I should get the {name : "StackOverFlow", reason : "Need help!"} as response (I will use fetch() to get the response) in the redirected client side HTML. 我应该在重定向的客户端HTML中获得{name:“ StackOverFlow”,reason:“需要帮助!”}作为响应(我将使用fetch()获取响应)。

What you'll want to do is setup your response object to look something like the below: 您要做的是将响应对象设置为如下所示:

 res.send({name : "StackOverFlow", reason : "Need help!", redirect_path: "/user/me"}); 

And then in the function callback on your client (where you're making the fetch request), you'll want to pickup the value of response.redirect_path and pass it into a JS redirect method. 然后,在客户端上的函数回调中(您在其中进行提取请求),您将希望获取response.redirect_path的值并将其传递给JS重定向方法。

You could use something like: location.href = response.redirect_path 您可以使用类似于: location.href = response.redirect_path

Example usage (on the client-side) 用法示例(在客户端)

 fetch("http://yousite.com/endPoint") .then((resp) => resp.json()) // Transform the data into json .then(function(response) { if (response.redirect_path) { //optional check to see if a redirect path exists location.href = redirect_path; } }) }) 

Bear in mind, I'm assuming that the argument passed in your fetch response callback function is called 'response', if it is 'res' or something else, you'll have to adjust the code above accordingly. 请记住,我假设在您的提取响应回调函数中传递的参数称为“ response”,如果它是“ res”或其他名称,则必须相应地调整上面的代码。

You should send json response to client side and under success function of your ajax call use window.open(redirecturl) 您应该将json响应发送到客户端,并在ajax调用的成功功能下使用window.open(redirecturl)

Let me know if it didn't help 让我知道是否有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM