我从网址获取参数时遇到了一些麻烦。我在服务器端使用Express(4.16.3),并使用Axios发出请求。但我似乎无法从Express中的URL中获取该参数。
这是我的代码:
在Express
中的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,而是记录params:{surveyId:':surveyId'}。我一直在研究,但似乎这是正确的方法。我也使用axios来提出请求:
在actions / index.js中(我用反应):
export const fetchOneSurvey = () => async dispatch => {
const res = await axios.get('/api/surveys/:surveyId');
dispatch({ type: FETCH_ONE_SURVEY, payload: res.data });};
不确定这是否相关: 在视图页面上,我没有http://localhost:3000/api/surveys/:surveyId,而是在React中设置了http://localhost:3000/surveys/:surveyId路由。当我转到http://localhost:3000/surveys/:surveyId时,它会像我在express中写的一样控制台日志(req.params),但我只得到一个字符串':surveyId'是params,而不是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);
}
});
};
答案 0 :(得分:0)
发布以下有关调试问题的详细信息
注意:如果您使用的是Windows操作系统,请使用命令提示符进行节点项目开发。我见过人们使用git bash进行节点项目开发,这会导致不必要的问题
以下是调试步骤
1.创建新目录forexample test
并使用npm init
2.安装快递npm install --save express
3.创建一个新文件for example 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://localhost:3000/api/surveys/llads的http请求。可以使用路径
中的路径参数llads
访问值surveyId
6.如果您可以在节点控制台中看到以下输出,那么程序正在按预期工作。这必须像这里描述的那样工作。
如果上述步骤产生了预期的输出,那么我就不会在您的路线代码中看到任何问题。
让我知道您的反馈意见。