尝试findById,但服务器未返回正确的状态响应

时间:2019-06-23 20:48:11

标签: javascript express axios

  1. 尝试使用Axios.get方法获取':id' S̶e̶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请求被暂停了

1 个答案:

答案 0 :(得分:0)

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