最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Express中的res.redirect有问题

网站源码admin15浏览0评论

Express中的res.redirect有问题

Express中的res.redirect有问题

我一直在尝试从搜索表单中输入我的位置,它会登录到控制台,但是res.redirect不会将我带到新的URL。 (给出的URL仅是示例)

const express = require('express');
const cors = require('cors');

// Utils
const geocode = require('./utils/geocode');
const forecast = require('./utils/weatherstack');

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors())

let location;

app.post('/search-location', async (req,res) => {
    try {
        location = await req.body.location
        return res.redirect('')
    } catch (e) {
        res.status(500).send(e)
    }    
})

app.listen(9000, () => {
  console.log("server is up and running on 9000");
})
回答如下:

我精简了您的代码,以下代码段为我提供了正确的重定向:

const express = require('express');

const app = express();

app.post('/search-location', async (req,res) => {
    try {
        return res.redirect('https://www.google')
    } catch (e) {
        res.status(500).send(e)
    }    
})

app.listen(9000, () => {
  console.log("server is up and running on 9000");
})
curl -X POST localhost:9000/search-location
*   Trying ::1:9000...
* Connected to localhost (::1) port 9000 (#0)
> POST /search-location HTTP/1.1
> Host: localhost:9000
> User-Agent: curl/7.69.1
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< X-Powered-By: Express
< Location: https://www.google
< Vary: Accept
< Content-Type: text/plain; charset=utf-8
< Content-Length: 44
< Date: Thu, 07 May 2020 16:37:00 GMT
< Connection: keep-alive
< 
* Connection #0 to host localhost left intact
Found. Redirecting to https://www.google

您的问题很可能是location = await req.body.location,因为req.body.location不是一个承诺(只是客户端解析的POST正文对象,无法等待它。

也许您打算将其包装在函数中:

location = await computeFunction(req.body.location)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论