У меня проблема с вызовом службы с моего веб-сайта при отправке компонента формы. Приветствуется любая помощь.
Веб-сайт, работающий на локальном хосте: 3000 Сервис, работающий на локальном хосте: 4041
Сервис никогда не получает при запросе с веб-сайта. Однако он работает с почтальоном.
Сообщение об ошибке в консоли через 30 секунд
Form.jsx: 115 POST http://localhost: 4041 / check_convention net :: ERR_EMPTY_RESPONSE
Есть идеи, почему?
ОБНОВЛЕНИЕ
Я вижу кое-что довольно интересное. При отправке он не попадает на сервер. Когда я открываю Firefox, открываю консоль, вижу запрос check_convention, пытаюсь отредактировать и повторно отправить запрос. Я заполняю тело и отправляю, затем оно проходит и показывает:
'{"ok": true, "error": "Невозможно проверить данные валюты"}'
Что говорит мне, что это сейчас работаю. Но только когда я редактирую и повторно отправляю. Почему?
cURL
curl "http://localhost:4041/check_convention" ^
-H "Referer: http://localhost:3000/execution" ^
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" ^
-H "Content-Type: application/json" ^
--data-binary "^{^\^"ccy1^\^":^\^"USD^\^",^\^"ccy2^\^":^\^"GBP^\^"^}" ^
--compressed
curl "http://localhost:4041/check_convention" ^
-X "OPTIONS" ^
-H "Connection: keep-alive" ^
-H "Accept: */*" ^
-H "Access-Control-Request-Method: POST" ^
-H "Access-Control-Request-Headers: content-type" ^
-H "Origin: http://localhost:3000" ^
-H "Sec-Fetch-Mode: cors" ^
-H "Sec-Fetch-Site: same-site" ^
-H "Sec-Fetch-Dest: empty" ^
-H "Referer: http://localhost:3000/execution" ^
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" ^
-H "Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,fr;q=0.7" ^
--compressed
Компонент формы
class Form extends React.Component {
constructor(props) {
this.state = {}
}
handleSubmit = event => {
this.postToCurrencyService()
event.preventDefault()
}
postToCurrencyService = () => {
const body = {ccy1: 'GBP', ccy2: 'USD'}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
};
// when inspecting I see it gets to fetch then continues and renders and does not hit .then
fetch('http://localhost:4041/check_convention', requestOptions)
.then(response => response.json())
.then(data => console.log(data ))
}
render () {
<div></div>
}
}
Приложение
const server = require("./server.js")
const port = process.env.PORT || 4041;
server.use((req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
})
server.listen(port, () => {
console.log(`server is running on port ${port}`)
})
Сервер
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/check_convention', (req, res) => {
const { ccy1, ccy2 } = req.body
let conventionChecker = new ConventionValidator(currencyList, currencyPriorityList)
if (conventionChecker.isValid(ccy1, ccy2)) {
const result = conventionChecker.asConvention(ccy1, ccy2);
return res.json({ok: true, result})
}
return res.json({ok: true, error: 'Unable to validate given currencies'})
})