SyntaxError: JSON中0 Express位置的意外token



我试图遵循本教程(https://levelup.gitconnected.com/introduction-to-express-js-a-node-js-framework-fa3dcbba3a98)连接Express与React Native通过。我有一个服务器.js脚本运行,它连接到我的ip上的客户端(App.tsx),端口3000。服务器和应用程序在不同终端的同一设备上同时运行。服务器能够很好地接收GET请求,因为当应用程序启动时,useEffect函数调用GET请求,服务器发送消息。然而,我的POST请求,其中包含一个内容体设置为JSON.stringify("hello world")不工作。当我按下按钮时,服务器脚本返回以下错误:

SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
...

我假设我正在发送格式错误的json,或者没有正确设置内容类型,但我还没有能够找出确切的问题。

应用程序。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}`));

首先,您不再需要显式地包含body-parser。它现在与Express捆绑在一起,可以通过以下功能使用…

app.use(express.json())
app.use(express.urlencoded()) // extended = true is the default

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" })
})

或者,如果您确实想发布JSON字符串文字,则需要像这样配置JSON中间件

app.use(express.json({ strict: false }))

strict

启用或禁用只接受数组和对象;当被禁用时,将接受JSON.parse接受的任何内容。

在这种情况下,您的"hello world"字符串将出现在req.body

为我添加

res.header('Access-Control-Allow-Origin', '*');

解决了问题

最新更新