简体   繁体   English

发布请求后重定向到另一个 url (AJAX, EXPRESS)

[英]Redirect to another url after post request (AJAX, EXPRESS)

As a part of learning node.js servers I'm working on a little log-in website.作为学习 node.js 服务器的一部分,我正在开发一个小型登录网站。 There's a site you can open and enter your username which will then be sent through an ajax post request to the server and saved into an array of all users.您可以打开一个站点并输入您的用户名,然后该用户名将通过 ajax 发布请求发送到服务器并保存到所有用户的数组中。 I wanna make it so that after you submit your username, you will be redirected to another page, unique for every username, where you will be able to see the information about you username.我想让它在您提交用户名后,您将被重定向到另一个页面,每个用户名都是唯一的,您将能够在其中看到有关您的用户名的信息。 Sort of a 'manage your account' site.有点像“管理您的帐户”网站。

However, I can't seem to figure out a way to redirect me to this page after I have submitted an username.但是,在我提交用户名后,我似乎无法找到将我重定向到此页面的方法。

Say for example you submit a username 'kokot' and it's the 3rd username that's been submitted so far.例如,您提交了一个用户名“kokot”,这是迄今为止提交的第三个用户名。 Thus, in the 'players' array, your user object will look something like this {id: 2, username: 'kokot'} .因此,在 'players' 数组中,您的用户 object 看起来像这样{id: 2, username: 'kokot'} Now I want to redirect you to the url localhost:2000/players/2 to see the info about your specific username.现在我想将您重定向到 url localhost:2000/players/2以查看有关您的特定用户名的信息。

NODE JS节点JS

const express = require('express');
const server = express();
const bodyParser = require('body-parser');

server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());

let players = [];

//loads the home page
server.get('/', (req, res) =>{
    res.sendFile(__dirname + '/home.html');
});

//loads the page with the list of players
server.get('/players', (req, res) =>{
    res.send(players);
});

server.get('/player/:id', (req, res) =>{
    res.send(players[req.params.id]);
});

//takes a new username and saves it to players array
server.post('/', (req, res) =>{
    console.log('NEW PLAYER: ' + req.body.username);

    players.push({
        id: players.length,
        username: req.body.username
    });
});








/////////////////////////////////////////////////////////////////////////////
server.listen(2000, () => console.log('LISTENING ON PORT 2000'));

HTML HTML

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Home</title>
</head>
<body>

    <h1>PISKVOREC</h1>

    <form id="userForm">
        username
        <input type="text" name="text" id="userFormInput">
        <input type="submit" name="Submit" id="userFormSubmit">
    </form>


<script>
    $(document).ready(()=>{

        let homeUrl = 'http://localhost:2000';

        let $userForm = $('#userForm');
        let $userFormSubmit = $('#userFormSubmit');


        //submits a new username to the server
        $userFormSubmit.click(() =>{
            $.post(homeUrl, {
                username: $('#userFormInput').val()
            }, function(){
                console.log('USERNAME SUBMITTED TO SERVER');
            });

            $.
        });
////////////////////
    });
</script>
</body>
</html>

Thank you for you responses and ideas谢谢你的回复和想法

Have a nice day祝你今天过得愉快

Sure, see below:当然,请看下面:

server.post('/', (req, res) =>{
    console.log('NEW PLAYER: ' + req.body.username);

    players.push({
        id: players.length,
        username: req.body.username
    });

    res.redirect(`/player/${req.body.username}`);
});

UPDATE Demo with vanilla Express.js app使用 vanilla Express.js 应用程序更新演示

app.js应用程序.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

app.post('/this', (req, res, next) => {
  res.redirect(`/that/${req.body.username}`);
});

app.get('/that/:id', (req, res, next) => {
  res.send(req.params);
});

module.exports = app;

index.hbs索引.hbs

<form method="post" action="/this">
    <input id="username" name="username" value="vader" type="text" />
    <button type="submit">Submit</button>
</form>

results in a redirect to: http://localhost:3000/that/vader导致重定向到: http://localhost:3000/that/vader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM