我有一個名為 json 的檔案data.json,我希望它的內容成為postData函式中 POST 請求的主體。
如何讀取內容或將內容作為我const body在 nodeJS 中的變數的值?
資料.json
{"name":"John", "age":30, "car":null}
索引.js
function postData() {
**const body = [];**
const headers = {
"Content-type": "application/json",
};
axios
.post(`${BASE_URL}/data`, body, { headers })
.then((response) => {
if (response.status === 200) {
console.log("Your Data has been saved!");
}
})
.catch((e) => {
console.error(e);
});
}
postData();
uj5u.com熱心網友回復:
在你的情況下, then-catch :
import file from "./your-path-file"
// OR
const file = require("./your-path-file");
function postData() {
const body = file;
const headers = {
"Content-type": "application/json",
};
axios
.post(`${BASE_URL}/data`, body, { headers })
.then((response) => {
if (response.status === 200) {
console.log("Your Data has been saved!");
const data = response.json(); // Get the data (response) from the request
console.log(data); // log the data - and you can assign it to variable, and use it.
}
})
.catch((e) => {
console.error(e);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/535360.html
上一篇:通過另一個函式運行匯入的函式
