我在埠 3001 上運行的節點 js 上構建了一個 API 服務,并在埠 3000 上運行了一個使用 REACT 和運行的 Web UI。我必須以 JSON 格式將詳細資訊從網頁發布到 API。我可以訪問 API,但是我無法在 API 上獲取 JSON。它作為 {} 接收。但是,郵遞員的 API 作業正常。
有人可以分享一下我失蹤的地方。
Source code of API
const util = require('util')
const request = require("request");
const express = require('express')
const app = express();
const port = 3001
app.use(express.json());
app.use(express.urlencoded( {extended: false}));
const bodyParser = require('body-parser');
const { json } = require('express/lib/response');
app.post('/PostPatronDetailsone',(req,res) => {
async function run() {
try {
console.log('Request received from REACT ONE');
// parse application/json
app.use(bodyParser.json())
console.log(req.body);
// Respond back
res.send('Transaction Sent');
} finally {
// Ensures that the client will close when you finish/error
}
}
run().catch(console.dir);
});
app.listen(port, () => console.log('Server is listening at port ' port));
Code Snippet of Web making the HTTP POST
import React from 'react';
class Signup extends React.Component {
constructor(props) {
super(props);
this.state = {
postId: null
};
}
async componentDidMount() {
// Simple POST request with a JSON body using fetch
let payload = {'first_name': 'TEST' };
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
const requestOptions = {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json','Accept':'application/json' },
body: data,
redirect: 'follow'
};
var response = await fetch('http://localhost:3001/PostPatronDetailsone', requestOptions);
var data1 = await response.json();
var data2 = data1.text();
alert(data2);
//this.setState({ postId: data1.insertedid });
}
render() {
const { postId } = this.state;
return (
<div className="card text-center m-3">
<h5 className="card-header">Simple POST Request</h5>
</div>
);
}
}
export default Signup;
Console Output of API Service
Server is listening at port 3001
Request received from REACT ONE
{}
Request received from REACT ONE
{}
uj5u.com熱心網友回復:
這是因為您發送 formData,而是將物件字串化并將其發送到 body,如下所示:
async componentDidMount() {
// Simple POST request with a JSON body using fetch
let payload = {first_name: 'TEST' };
const requestOptions = {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json','Accept':'application/json' },
body: JSON.stringify(payload ),
redirect: 'follow'
};
var response = await fetch('http://localhost:3001/PostPatronDetailsone', requestOptions);
var data1 = await response.json();
var data2 = data1.text();
alert(data2);
//this.setState({ postId: data1.insertedid });
}
uj5u.com熱心網友回復:
請按如下方式更改代碼:
let payload = {'first_name': 'TEST' };
fetch('http://localhost:3001/PostPatronDetailsone',{
body:JSON.stringify(payload),
method:'post',
mode: 'no-cors',
headers: {
"Content-Type": "application/json"
},
}).then((res)=>res.json()).then((data)=>console.log(data));
并且從后端的控制器中洗掉該行,因為您已經在使用 express.json() 這相當于該行:
app.use(bodyParser.json()) // remove it
uj5u.com熱心網友回復:
這里有 3 個關鍵問題:
- 您正在發布一個 FormData 物件(它被轉換為 multipart/form-data 編碼)而不是 JSON
- 您正在設定
no-cors模式,這會導致瀏覽器靜默丟棄任何需要 CORS 權限的指令(例如設定application/json內容型別或讀取回應) text()從 JSON 決議的任何內容都不會有任何方法
const data = {'first_name': 'TEST' };
const payload = JSON.stringify(data)
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json','Accept':'application/json' },
body: payload,
redirect: 'follow'
};
const response = await fetch('http://localhost:3001/PostPatronDetailsone', requestOptions);
const parsed_json = await response.json();
console.log(parsed_json);
您還需要更改服務器端代碼以授予 JavaScript 讀取回應和發送 JSON 格式請求的權限。為此使用該cors模塊。
app.use(cors());
另請注意,正文決議中間件需要在應用程式啟動時設定,而不是在路由中間。body-parser 模塊已經過時,因為 Express 現在已經內置了它的功能。
以下是好的:
app.use(express.json());
以下是不好的:
const bodyParser = require('body-parser');
和
app.use(bodyParser.json())
您的路線代碼不需要比以下內容更復雜:
app.post('/PostPatronDetailsone', async (req,res) => {
console.log('Request received from REACT ONE');
console.log(req.body);
res.json('Transaction Sent');
});
請注意,由于您試圖在客戶端代碼中將回應決議為 JSON,因此我必須更改send為json以便服務器輸出 JSON 而不是純文本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/432061.html
