Я создал приложение реагирования, используя create-Reaction-app, и сервер express, используя генератор express. Мое приложение реакции работает на http://localhost: 3000 , а мой express сервер работает на http://localhost: 8080 . В моем компоненте я делаю запрос POST на мой сервер express, который успешно выполняет мой код маршрутизатора express, возвращая код состояния ответа 200. Однако консоль клиента регистрирует следующую ошибку и не получает ответ:
Proxy error: Could not proxy request /components/findAlbumArt from localhost:3000 to http://localhost:8080.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
В браузере на вкладке сети я вижу, что запрос findAlbumArt
теперь имеет статус (canceled)
.
Мой код реакции:
import React, { Component } from "react";
class Search extends Component {
constructor(props) {
super(props);
this.state = { value: "" };
}
handleChange = (event) => {
this.setState({ value: event.target.value });
};
handleSubmit = async (event) => {
let response = await fetch("/components/findAlbumArt", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
value: this.state.value,
}),
});
response = await response.json();
this.props.setAlbumArt(response.albumArtUrl);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Find an album that you love:{" "}
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>{" "}
<input type="submit" value="Submit" />
</form>
);
}
}
export default Search;
Мой express код:
const express = require("express");
const cache = require("../bin/cache/cache");
const axios = require("axios");
const router = express.Router();
router.post("/findAlbumArt", async (req, res, next) => {
res
.status(200)
.json({
albumArtUrl:
"https://i.scdn.co/image/ab67616d0000b2739feadc48ab0661e9b3a9170b",
});
// I commented out my other code to simply test returning a success response
});
module.exports = router;
Другие соответствующие файлы:
приложение. js
const express = require("express");
const path = require("path");
const createError = require("http-errors");
const logger = require("morgan");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
let app = express();
const indexRouter = require("./routes/index");
const componentsRouter = require("./routes/components");
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/components", componentsRouter);
app.use("/", indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
express пакет. json
{
"name": "onboarding",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "nodemon ./bin/www",
"start": "node ./bin/www"
},
"dependencies": {
"async-redis": "^1.1.7",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1",
"pug": "2.0.0-beta11"
}
}
пакет клиента. json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080",
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Любая помощь будет принята с благодарностью. Спасибо!