我正在尝试按照此教程(https://levelup.gitconnected.com/introduction-to-express-js-a-node-js-framework-fa3dcbba3a98)连接Express和React Native。我有一个运行server.js脚本的服务器,在我的IP、端口3000上连接到客户端(App.tsx)。服务器和应用程序在同一设备上分别在不同终端中同时运行。服务器可以正常接收GET请求,因为当应用程序启动时,useEffect函数会调用一个GET请求,然后服务器发送一个消息。但是我的POST请求,其中包含设置为
JSON.stringify("hello world")
的内容主体,并不起作用。每当我按下按钮时,服务器脚本都会返回以下错误:SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
...
我猜想我发送的json格式不正确,或者没有正确设置内容类型,但我一直没有找到确切的问题。
App.tsx文件(其中myip是我的IP地址):
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, ScrollView, TouchableOpacity, TextInput } from 'react-native';
export default function App() {
const [response, setResponse] = useState();
useEffect(() => {
fetch("http://myip:3000/get")
.then(res => res.json())
.then(res => console.log(res.theServer))
}, []);
async function handleSubmit() {
console.log('button press');
const response = await fetch("http://myip:3000/wow/post", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify("hello world")
});
const body = await response.text();
setResponse({ responseToPost: body });
}
return (
<View style={styles.container}>
<TouchableOpacity onPress={handleSubmit}>
<Text>Submit</Text>
</TouchableOpacity>
</View>
}
...
});
server.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/get", (req, res) => {
res.send({ theServer: "hElLo FrOm YoUr ExPrEsS sErVeR" });
});
app.post("/wow/post", (req, res) => {
console.log(req.body);
res.send(`Here is what you sent me: ${req.body.post}`);
});
app.listen(port, () => console.log(`listening on port ${port}`));
app.use(bodyParser.json());
- CertainPerformancepost
属性?你没有发送它。 - Bravoapp.use(express.json())
。内置的中间件只是 body-parser 的替代品。 - Phil