gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:26:07 27 4
gpt4 key购买 nike

  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. 目前我无法设置组件的状态。我得到一个空对象

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

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);

快速 Controller

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}/`);
});

控制台/网络和 postman 中显示的错误。看起来 http.get 请求已停止

最佳答案

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

关于javascript - 尝试 findById 但服务器未返回正确的状态响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727620/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com