gpt4 book ai didi

javascript - 在 Express.js 中构建 API,获取 "Cannot GET/api"

转载 作者:行者123 更新时间:2023-12-01 00:48:58 24 4
gpt4 key购买 nike

当我输入查询时,无法获取/api,我转到 localhost:3000 并得到我期望返回的内容,即“随机用户 API”,但是当我输入查询时 http://localhost:3000/api?results=100 。我收到无法 GET/api 的消息。不知道从哪里来

index.js

let express = require('express'),
route = require('./routes/routes.js');

let app = express();

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

app.use(express.static(__dirname + '/public'));

app.get('/', route.index);
app.get('/app', route.api);

app.listen(3000);

routes.js

var myNames = require("../names.json");

var MAX_RESULTS = 1000;

exports.index = function(req, res) {
res.send("Random User API");
};

exports.api = function(req, res) {
this.results = req.query.results;
this.seed = req.query.seed;
res.send(generateNames(this.results, this.seed));
};

function generateNames(results, seed) {
this.results = results;
if (this.results > MAX_RESULTS) {
this.results = MAX_RESULTS;
}
this.seed = seed;

var rand = require("random-seed").create(this.seed);
var gender;
var picRand;
var picNum;
var genRand;
var firstname, lastname, address, city, state, postcode;
var username;
var phone;

var names = {
results: []
};
for (let i = 0; i < this.results; i++) {
genRand - rand(2);
picRand = rand(150) + 1;

if (picRand < 10) {
picNum = "00" + picRand;
} else if (picRand < 100) {
picNum = "0" + picRand;
} else {
picNum = "" + picRand;
}

if (genRand == 0) {
gender = "male";
picLarge = "http://localhost:3000/images/m" + picNum + ".jpg";
firstname = myNames.male_names[rand(myNames.male_names.length)];
} else {
gender = "female";
picLarge = "http://localhost:3000/images/f" + picNum + ".jpg";
firstname = myNames.female_names[rand(myNames.female_names.length)];
}

lastname = myNames.last_names[rand(myNames.last_name.length)];

address =
myNames.last_names[rand(myNames.last_names.length)] +
" " +
myNames.street_types[rand(myNames.street_types.length)];

postcode = rand(90000) + 10000;
phone = rand(999) + 120 + "-" + rand(999) + 100 + "-" + rand(9999) + 1000;

var person = {
gender: gender,
name: {
first: firstname,
last: lastname
},
location: {
street: address,
city: city,
state: state,
postcode: postcode
},
email: email,
login: {
username: username,
password: password
},
dob: {
date: date,
age: age
},
phone: phone,
cell: cell,
picture: {
large: picLarge,
medium: picMedium,
thumbnail: thumbnail
}
};
names.results.push(person);
}
return names;
}

我希望我的数据以 JSON 格式显示

最佳答案

您正在使用/app 而不是/api

app.get('/app', route.api);

关于javascript - 在 Express.js 中构建 API,获取 "Cannot GET/api",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57139550/

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