gpt4 book ai didi

javascript - 发布 - 无法获取错误 - 本地服务器

转载 作者:行者123 更新时间:2023-11-28 04:59:44 24 4
gpt4 key购买 nike

我正在尝试使用本地服务器创建一个 API 进行测试。路线“GET”工作正常,但是“POST”有问题,它返回“无法获取/添加/名称”。我正在使用 node.js 和 Express 开发 API。当路由设置为“POST”时,为什么我会收到 get 消息?问题出在哪里?

var fs = require('fs');
var data = fs.readFileSync('events.json');
var allEvents = JSON.parse(data);

console.log(allEvents);
console.log('Server running.');

var express = require('express');
var app = express();
var sever = app.listen(3000, listening);

function listening() {
console.log('Serving...');
}

app.use(express.static('website'));

//GET and send all data from JSON
app.get('/all', sendAll);

function sendAll(request, response) {
response.send(allEvents);
}

//POST new data to JSON
app.post('/add/:name', addData);

function addData(request, response) {

var newData = request.params;
var name = newData.name;
var eventType = newData.eventType;
var reply;

// var newEvent = {
// name: ":name",
// eventType: ":eventType",
// };

var newData = JSON.stringify(allEvents, null, 2);
fs.writeFile('events.json', newData, finished);

function finished(err) {
console.log('Writting');
console.log(err);
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}

请求

$(function() {
//HTML
var $list = $('#list');

var jsonURL = '../events.json'

$.ajax({
type: 'GET',
url: '/all',
success: function(data) {
console.log('Data received', data);
$.each(data, function (type, string) {
$list.append('<li>' + type + " : " + string + '</li>');
});
},
error: function (err) {
console.log('Error, data not sent.', err);
}
});

$('#submit').on('click', function () {

// var newEvent = {
// name: $name.val(),
// eventType: $eventType.val(),
// };

var name = $('#fieldName').val();
var eventType = $('#fieldEventType').val();
console.log(name);

$.ajax({
type: 'PUT',
url: '/add/' + name,
success: function (addData) {
$list.append('<li>name: ' + name + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
});

提前谢谢您。

最佳答案

对于测试POST请求,可以使用Postman来测试。如果使用浏览器调用api,将是GET方法而不是POST。

POST request in postman

关于javascript - 发布 - 无法获取错误 - 本地服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229469/

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