【发布时间】:2019-06-23 20:48:11
【问题描述】:
- 尝试使用 Axios.get 方法获取 ':id' S̶e̶r̶v̶e̶r̶̶i̶s̶̶r̶e̶s̶p̶o̶n̶d̶i̶n̶g̶̶w̶i̶t̶h̶̶a̶̶4̶0̶4̶
- 目前我无法设置组件的状态。我得到一个空对象
我尝试过调整控制器参数,但似乎无法弄清楚
loadProfile() {
axios.get('http://localhost:3000/api/companies/' + this.props.match.params.id)
.then(res => {
if (!res) {
console.log("404 error, axios cannot get response");
} else {
console.log(res.data);
this.setState({ company: res.data });
}
});
快速api路由
companyRoutes.route('/:id').get(company_controller.company_id_get);
快速控制器
exports.company_id_get = (req, res) => {
const id = req.params.id;
Company.findById( id, (company, err) => {
if(err) {
console.log("404 error", err);
}
else {
res.json(company);
}
})
}
服务器端代码
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors')
const passport = require('passport');
const app = express();
const users = require('./routes/api/users');
const companyRoute = require('./routes/api/companies');
app.use(express.static("static"));
//Bodyparser middleware
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB configuration
const db = require("./config.scripts/mongoKey").mongoURI;
// Connect to MonngoDB
mongoose.connect(
db, { useNewUrlParser: true }
)
.then((db) => console.log('MongoDB succesfully connected'))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
//Passport config
require('./config.scripts/passport.js')(passport);
//Routes
app.use('/api/users', users);
app.use('/api/companies', companyRoute);
//Redirect any server request back to index.html: To deal with CRS
app.get('/', function(req, res, next){
res.sendFile(path.join(__dirname, '../client', 'index.html'));
})
//Hostname and Port
//const hostname = '127.0.0.1';
const port = 3000;
app.listen(port, () => {
console.log(`Backend server is running at http://localhost:${port}/`);
});
控制台/网络和邮递员中出现的错误。看起来 http.get 请求被停止了
【问题讨论】:
-
请将相关的服务器端/快递代码添加到您的问题中。
标签: javascript express axios