gpt4 book ai didi

javascript - 使用node js发布请求

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:57 25 4
gpt4 key购买 nike

我正在尝试使用 node.js 发出发布请求,当我尝试运行它时,我得到的数据显示在控制台中,但没有显示 HTML 的正文。在控制台中我收到错误

app.js:4 POST http://localhost:8000/addAnimal net::ERR_EMPTY_RESPONSE
postData @ app.js:4
(anonymous) @ app.js:25
app.js:21 Uncaught (in promise) TypeError: Failed to fetch

看起来该功能正在运行,但实际的发布请求部分却不起作用。我一生都无法弄清楚我做错了什么。

这是我的代码:

服务器.js:

projectData = {};

/* Express to run server and routes */
const express = require('express');

/* Start up an instance of app */
const app = express();

/* Dependencies */
const bodyParser = require('body-parser')
/* Middleware*/
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const cors = require('cors');
app.use(cors());

/* Initialize the main project folder*/
app.use(express.static('project1'));

const port = 8000;
/* Spin up the server*/
const server = app.listen(port, listening);
function listening(){
// console.log(server);
console.log(`running on localhost: ${port}`);
};

// GET route
app.get('/all', sendData);

function sendData (request, response) {
response.send(projectData);
};

// POST route
app.post('/add', callBack);

function callBack(req,res){
res.send('POST received');
}

// POST an animal
const data = [];


// TODO-Call Function



app.route('/addAnimal')
.get(function (req, res) {
res.sendFile('index.html', {root: 'project1'})
})
.post(function (req, res) {
data.push(req.body)
})

app.js

/* Function to POST data */
const postData = async ( url = '', data = {})=>{
console.log(data);
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
});

try {
const newData = await response.json()
// console.log(newData);
return newData.json()
}catch(error) {
console.log("error", error)
// appropriately handle the error
};
};

// TODO-Call Function

postData('/addAnimal', {animal:'lion'});

任何帮助将非常感激。

谢谢,迈克

最佳答案

💡 The only one reason why you got message like it, it's because you never send response to the client.

👨‍🏫 因此,您应该向客户端发送响应。例如,您可以查看下面的代码:👇

app.route('/addAnimal')
.get(function (req, res) {
res.sendFile('index.html', {root: 'project1'})
})
.post(function (req, res) {
data.push(req.body);
// send data to client
// you can change req.body with the object what you want to sent do the client
res.status(200).send(req.body);
})

📤更新:其他信息

Make sure you call the endpoint: http://localhost:8000/addAnimal.

前端:确保您的代码类似于下面的代码

const postData = async ( url = '', data = {})=>{
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
try {
console.log(await response.json());
return await response.json()
}catch(error) {
console.log("error", error);
};
};

希望对你有帮助🙏。

关于javascript - 使用node js发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59969360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com