【发布时间】:2018-04-16 18:36:51
【问题描述】:
我有一个问题,我正在创建一个使用 Express 的项目,但我不知道如何运行该项目,我尝试使用 concurrently 但失败了...
我想要的是获取 URL http://localhost:9000/people 的名称(由 express.js 生成)并在 this.state 中插入 persons。
有人可以帮助我吗?
我的package.json:
{
"name": "myapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"express": "^4.16.3",
"react": "^16.3.1",
"react-dom": "^16.3.1",
"react-scripts": "1.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:9000"
}
我的app.js 和axios.js:
import React, { Component } from 'react';
const axios = require("axios");
class App extends Component {
constructor(props) {
super(props);
this.state = {
elementsPerPage: 15,
currentPage: 0,
persons: [],
};
}
componentDidMount() {
axios.get("http://localhost:9000/person").then(res => {
this.setState({persons: res.data})})
}
....
我的express.js:
const express = require('express');
const app = express();
app.get('/person', (req, res) => {
res.send([{ id: 0, name: "123" },
{ id: 1, name: "123" },
{ id: 2, name: "123" },
{ id: 3, name: "123" },
{ id: 4, name: "123" },
{ id: 5, name: "123" },
{ id: 6, name: "123" },
{ id: 7, name: "123" },
{ id: 8, name: "123" },
{ id: 9, name: "123" },
{ id: 10, name: "123" },
{ id: 11, name: "123" }]
)
});
app.listen(9000, () => console.log('Running server on 9000'));
已经在尝试npm run dev npm start 而不是。
【问题讨论】:
-
那么你的问题什么时候开始。我的意思是你的应用程序失败了,转译失败了,还是你不能访问数据(axios 调用失败了吗?)
-
所以你提到你正在运行 npm start。如果您没有修改 react-scripts/start.js 中的任何内容,这将转换您的 react 应用程序并启动开发服务器。但是,此服务器不是您创建的快速服务器,因此您应该单独启动它。
-
@the_cheff 给出了那个错误:
Line 15: 'peoples' is not defined no-undef,我执行了这两个。 -
简短回答:您可能在第 15 行使用“peoples”而不是“people”。长答案:我不确定“peoples”是什么,我在您发布的代码中的任何地方都看不到它(当您说人,人民和人时,您是在谈论同一个变量吗?)。它看起来确实像一个 linting 错误。所以我猜这发生在编译时(所以你甚至不能访问应用程序吗?)。这意味着您在定义变量之前正在使用它。 eslint.org/docs/rules/no-undef 因此,请查看您的代码并找到您使用人员的地方而不定义它。
标签: node.js reactjs express axios