React 中 POST 和 Node.js 的问题

Problems with POST in React and Node.js

我正在学习如何结合使用 Node 和 React。我目前正在做的事情是以 React 形式从输入发布到 Node。

我有两个问题:

  1. 我在 async/await 获取请求。如果我将它更改为 fetch().then().then() 我就不会再遇到这个问题了,但我也想弄清楚如何这样做。

  2. 我也收到错误消息“Uncaught (in promise) SyntaxError: Unexpected token P in JSON at position 0”。

我很确定问题出在 React 方面。我之前让整个工作正常,但我删除了它并重新开始,因为那是我在学习时所做的。我之前的代码显然有些不同。我可以使用教程和网站弄清楚如何编写这种请求以使其工作,但也许这次我不会弄清楚出了什么问题,这会让我发疯。很明显,为了将数据获取到数据库中,在 Node 端还有更多的事情要做(我之前将数据获取到 Node 中),但我正在尝试在此之前解决这个问题。

server.js

const express = require('express');
const application = express();
const cors = require('cors');
application.use(cors());
application.use(express.json());
application.use(express.urlencoded({ extended: true }));

// routes are here
application.get('/', (request, response) => {
    response.send('Homepage');
});
application.get('/testAPI', (request, response) => {
    response.json('Test API working');
});
application.get('/register', (request, response) => {
    response.send('Register route');
});
application.post('/register', (request, response) => {
    response.send('POST received');
    console.log('POST received');
});

// listen to server
application.listen(8080, () => {
    console.log('Listening here...');
});

App.js

import { useState, useEffect } from 'react';

function App() {
  // basic state for things
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [data, setData] = useState('Data goes here');
  const [API, setAPI] = useState('Data from API goes here');

  useEffect(() => {
    fetch('http://localhost:8080/testAPI')
      .then(res => res.json())
      .then(data => setAPI(data));
  }, []);

  const readUsername = (e) => {
    setUsername(e.target.value);
  };

  const readPassword = (e) => {
    setPassword(e.target.value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const inputData = {
      username: {username},
      password: {password},
    };
    const requestCall = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(inputData),
    };
    const result = await fetch('http://localhost:8080/register', requestCall);
    console.log(result.json());
  };

  return (
    <div>
      <>
      <h1>Hello World!</h1>
      <form onSubmit={handleSubmit} method="POST">
        <label htmlFor="username" name="username" >Username: </label>
        <input htmlFor="username" name="username" onChange={readUsername} />
        <br/>
        <label htmlFor="password" name="password" >Password: </label>
        <input htmlFor="password" name="password" type="password" onChange={readPassword} />
        <br/>
        <button type="submit">Submit</button>
      </form>
      <h1>{API}</h1>
      </>
    </div>
  );
}

export default App;

服务器正在发回 文本,而不是JSON。所以任何时候你这样做:

res.json()

你会得到那个错误。将这些实例替换为:

res.text()

此外,这会将 promise 记录到控制台:

console.log(result.text());

因为.text()(和.json())是一个异步操作。等待结果:

console.log(await result.text());