fig*_*bar 5 javascript express react-native
我正在尝试按照本教程(https://levelup.gitconnected.com/introduction-to-express-js-a-node-js-framework-fa3dcbba3a98)通过 . 我正在运行一个 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>)
...
Run Code Online (Sandbox Code Playgroud)
我假设我发送的 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>
}
...
});
Run Code Online (Sandbox Code Playgroud)
服务器.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}`));
Run Code Online (Sandbox Code Playgroud)
首先,您不再需要显式包含body-parser
. 它现在与 Express 捆绑在一起,并可通过以下功能使用...
app.use(express.json())
app.use(express.urlencoded()) // extended = true is the default
Run Code Online (Sandbox Code Playgroud)
JSON 解析中间件默认配置为处理对象。虽然像这样的字符串文字"hello world"
是有效的 JSON,但它不是框架所期望的,因此会出现错误。
由于您似乎正在尝试访问req.body.post
,因此您应该使用这样的结构发送数据
fetch("http://myip:3000/wow/post", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ post: "hello world" })
})
Run Code Online (Sandbox Code Playgroud)
或者,如果您确实想发布 JSON 字符串文字,则需要像这样配置 JSON 中间件
app.use(express.json({ strict: false }))
Run Code Online (Sandbox Code Playgroud)
strict
启用或禁用仅接受数组和对象;当禁用时将接受任何
JSON.parse
接受的东西。
在这种情况下你的"hello world"
字符串会出现在req.body
归档时间: |
|
查看次数: |
7133 次 |
最近记录: |