我有一个问题,我正在创建一个使用Express的项目,但我不知道如何运行该项目,我尝试使用concurrently
但是失败了......
我想要的是获取网址http://localhost:9000/people
的名称(由express.js
生成)并在persons
中插入this.state
。
有人可以帮助我吗?
我的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
而不是。
答案 0 :(得分:0)
试试这个
componentDidMount() {
axios.get("/people").then(res => { //dont use full address
this.setState({peoples: res.data})})
}
如果这不起作用, 请尝试遵循本教程How to get create-react-app to work with a Node.js back-end API