Reactjs 如何从服务器端的express/mongo/mongoose中的URL获取参数Id,客户端的axios/react/redux

Reactjs 如何从服务器端的express/mongo/mongoose中的URL获取参数Id,客户端的axios/react/redux,reactjs,express,mongoose,parameters,axios,Reactjs,Express,Mongoose,Parameters,Axios,我在从url获取参数时遇到一些问题。我在服务器端使用Express(4.16.3),并使用Axios发出请求。但我似乎无法从Express中的url获取参数 这是我的密码: 在Express中的my Route.js上 app.get('/api/surveys/:surveyId', (req, res, next) => { var id = req.params.surveyId; console.log(req.params); // it gets pa

我在从url获取参数时遇到一些问题。我在服务器端使用Express(4.16.3),并使用Axios发出请求。但我似乎无法从Express中的url获取参数

这是我的密码:

在Express中的my Route.js上

app.get('/api/surveys/:surveyId', (req, res, next) => {
    var id = req.params.surveyId;
    console.log(req.params);
    // it gets  params {surveyId: ':surverId'}
    res.send('Hello World');
});
因此,它不获取实际id,而是记录参数:{surveyId:':surveyId'}。我一直在研究,但似乎这是正确的方法。我还使用axios发出请求:

在actions/index.js中(我使用react):

不确定这是否相关: 在查看页面上,我在React中设置了路由,而不是have。当我转到时,它会像我在express中写的那样记录控制台日志(req.params),但我只得到一个字符串:surveyId是参数,而不是url上的实际id

请问有人能帮我吗?我尝试过许多不同的方法,但似乎都不管用。我事先非常感谢大家

======额外部分====== 这是我的index.js:

const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const bodyParser = require('body-parser');
const keys = require('./config/keys');

require('./models/User');
require('./models/Survey');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

app.use(bodyParser.json());
app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieKey]
    })
);

app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app);
require('./routes/billingRoutes')(app);
require('./routes/surveyRoutes')(app);

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'));

    const path = require('path');
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
    });
}
我的调查模型路线js:

const _ = require('lodash');
const Path = require('path-parser');
const { URL } = require('url');
const mongoose = require('mongoose');
const requireLogin = require('../middlewares/requireLogin');
const requireCredits = require('../middlewares/requireCredits');
const Mailer = require('../services/Mailer');
const surveyTemplate = require('../services/emailTemplates/surveyTemplate');

const Survey = mongoose.model('surveys');

module.exports = app => {
    app.get('/api/surveys', requireLogin, async (req, res) => {
        const surveys = await Survey.find({ _user: req.user.id }).select({
            recipients: false
        });

    res.send(surveys);
});

app.get('/api/surveys/:surveyId/:choice', (req, res) => {
    res.send('thanks for voting');
});

app.get('/api/surveys/:surveyId', (req, res, next) => {
    var id = req.params.surveyId;
    console.log(id);
    // it gets  params {surveyId: ':surverId'}
    res.send('Hello World');
});

app.post('/api/surveys/webhooks', (req, res) => {
    // console.log(req.body);
    // res.send({});
    const p = new Path('/api/surveys/:surveyId/:choice');

    const test = _.chain(req.body)
        .map(({ email, url }) => {
            const match = p.test(new URL(url).pathname);
            if (match) {
                return {
                    email,
                    surveyId: match.surveyId,
                    choice: match.choice
                };
            }
        })
        .compact()
        .uniqBy('email', 'surveyId')
        .each(({ surveyId, email, choice }) => {
            Survey.updateOne(
                {
                    // have to add _ to keys as mongoDB rule, mongoose doensn't need.
                    _id: surveyId,
                    recipients: {
                        $elemMatch: { email: email, responded: false }
                    }
                },
                {
                    $inc: { [choice]: 1 },
                    $set: { 'recipients.$.responded': true },
                    lastResponded: new Date()
                }
            ).exec();
        })
        .value();

    console.log(test);

    res.send({});
});

app.post('/api/surveys', requireLogin, requireCredits, async (req, res) => {
    const { title, subject, body, recipients } = req.body;

    const survey = new Survey({
        // map(email => ({ email }) === map(email =>{ return {email: email}})
        title,
        body,
        subject,
        recipients: recipients
            .split(',')
            .map(email => ({ email: email.trim() })),
        _user: req.user.id,
        dateSent: Date.now()
    });

    // send an email
    const mailer = new Mailer(survey, surveyTemplate(survey));
    try {
        await mailer.send();
        await survey.save();
        req.user.credits -= 1;
        const user = await req.user.save();

        res.send(user);
    } catch (err) {
        res.status(422).send(err);
    }
});
};

在下面发布调试问题的详细信息

注意:如果您使用的是Windows操作系统,请使用命令提示符进行节点项目开发。我见过有人使用GitBash进行节点项目开发,这会导致不必要的问题

以下是调试步骤

1.创建一个新目录
example test
,并使用
npm init

2.安装express
npm安装--保存express

3.创建一个新文件
,例如index.js
,并使用下面的代码

test/index.js

var express= require("express");
var app = express();

app.get("/api/surveys/:surveyId",(req,res,next)=>{
    console.log(req.params.surveyId);
    res.send('Hello World');
});

var server= app.listen(3000,()=>{
    console.log("port started at ",server.address().port);
})
4.启动程序
node index.js

5.从浏览器触发http请求。可以使用路由中的路径参数
surveyId
访问值
llads

6.如果您可以在节点控制台中看到以下输出,则程序正常工作。这必须按照这里描述的那样工作

如果上面的步骤产生了预期的输出,那么我认为您的路由代码中没有任何问题


让我知道您的反馈。

它会记录{surveyId:':surverId'},因为您正在打印req.params。您必须打印id或req.params.surveyId才能获得预期的结果即使我打印id,它仍然显示“:surveyId”,我记录了req,并且它仍然显示params{surveyId:':surveyId'}…:(@llads检查我的答案。我发布它是为了调试你的问题。它可以为你解决问题提供一些线索。而且我在你发布的代码中没有发现问题。使用react并不重要。你可以通过BrowserThank@divine触发http请求来测试你的路由。谢谢@divine,我已经按照你的调试步骤进行了操作,结果是expe反恐执行官。但是,在实际项目中,我的index.js文件中没有路由。我将在编辑部分添加我的index.js文件和调查模型route js。如果您能看一看,看看是否有任何线索,那就太好了。@index.js中有路由逻辑的LLAD可能无法解决您的问题。您的完整代码在哪里?我要上厕所k在it你真的确定你的请求到达了路由/api/surveys/:surveyId吗?在这个方法中添加额外的console.log来确认这个特定的路由是否被触发。你能通过浏览器和测试触发这个路由吗?啊,我知道了,我测试了/api/surveyId/:surveyId,它确实抓到了id。我想这是出了问题我的前端路由。非常感谢您为我解决这个问题。我还有一个问题,但如果您不回答也可以,因为它与此不太相关。我想将数据从backend/api/surveys/:surveyId导入前端视图/surveys/:surveyId,我应该在哪里查看,而不是发送res.send('Hello World');您可以像res.send({“data”:dataJSONObject})那样发送json对象;.Express将自动识别其为json对象,并在响应中将contenttype设置为application/json。您可以在axios中获取此对象。然后回调。通过这种方式,您可以将数据从服务器路由发送到前端代码
test/index.js

var express= require("express");
var app = express();

app.get("/api/surveys/:surveyId",(req,res,next)=>{
    console.log(req.params.surveyId);
    res.send('Hello World');
});

var server= app.listen(3000,()=>{
    console.log("port started at ",server.address().port);
})