【问题标题】:Trying to findById but server is not return proper status response尝试 findById 但服务器未返回正确的状态响应
【发布时间】:2019-06-23 20:48:11
【问题描述】:
  1. 尝试使用 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̶
  2. 目前我无法设置组件的状态。我得到一个空对象

我尝试过调整控制器参数,但似乎无法弄清楚

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


【解决方案1】:

看来您在路线http:/localhost:3000/api/companies/... 中忘记了/。将其更改为 http://... 应该可以解决您的问题。

【讨论】:

  • 我修复了缺失的类型。但是现在看来我无法设置状态。我对 setState 做了一个小调整以检查是否可以存储 param.id 但我得到一个空对象javascript this.setState({ company: res.data, company_id: this.props.match.params.id });
猜你喜欢
  • 1970-01-01
  • 2011-05-16
  • 2012-05-16
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多