繁体   English   中英

将 URL 参数从 React 发送到 Node JS API

[英]Send URL params from React to Node JS API

我正在使用 MERN 创建一个网站,我正在努力将 URL 中的用户名传递给 React。

我想从一个用户那里获取我在 URL 中传递的每一篇博客文章。 为此,我在server.js中使用find() 这适用于我的 NodeJS 服务器http://localhost:3333/

app.get('/blog/:username', (request, reponse) => {

mongo.connect(url, function (err, db) {
    var dbo = db.db("mern-pool");
    var cherche_user = request.params.username; 
    dbo.collection("posts").find({username: cherche_user}).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        var students = result;
        reponse.send(result);
        db.close();
        });
    });
});

我需要将该数据传递到我的 React blog-indiv组件中。 但是这不起作用,我的console.log(this.state)呈现一个空数组。

当我将axios.get('http://localhost:3333/blog/:username')更改为axios.get('http://localhost:3333/blog/user123')时,它确实有效

    export default class BlogIndiv extends Component {

    constructor() {
        super();
        this.state = {
            posts: []
        };
    }

    componentDidMount() {
        axios.get('http://localhost:3333/blog/:username')
            .then(response => {
                this.setState({ posts: response.data });
                console.log(this.state);
            })
    }

    render() {
        return(
            <div>
                <h1>HE</h1>
                {this.state.posts.map(e  => {
                        return (
                            <Sub title={e.title} 
                                content={e.content}
                                author={e.username}
                            />
                        )}
                    )}
            </div>
        ) 
    }
}

你可以像这样使用反引号传递它。

let anyvar = user123
axios.get(`http://localhost:3333/blog/${anyvar}`)

希望这能回答你的问题! 快乐编码!

您可以尝试将您的 axios url 更改为以下内容:

axios.get('http://localhost:3333/blog/'+id)

在收到 function 中的 ID 后,如下所示:

componentDidMount(id)

axios.get('http://localhost:3333/blog/:username')更改为

const username = "something"
axios.get(`http://localhost:3333/blog/${username}`)

你可以安装npm i @eneto/axios-es6-class

然后创建UserApi.tsUserApi.js

import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { Api } from '@eneto/axios-es6-class';
import { Credentials, Token, User } from './interfaces';
import { axiosConfig, API_BASE_URL } from "./axios-config";

class UserApi extends Api {
    public constructor (config?: AxiosRequestConfig) {
        super(config);


        // this middleware is been called right before the http request is made.
        this.interceptors.request.use((param: AxiosRequestConfig) =>
            ...param,
            baseUrl: API_BASE_URL
        }));

        // this middleware is been called right before the response is get it by the method that triggers the request
        this.interceptors.response.use((param: AxiosResponse) => ({
            ...param
        }));

        this.userLogin = this.userLogin.bind(this);
        this.userRegister = this.userRegister.bind(this);
        this.getAllUsers = this.getAllUsers.bind(this);
        this.getById = this.getById.bind(this);
        this.getBlogsByUiserId = this.getBlogsByUiserId.bind(this);
    }

    public getBlogsByUiserId (id: number): Promise<Blogs[]> {
        return this.get<Blogs[], AxiosResponse<Blogs[]>>(`/blog/${id}`)
           .then((response: AxiosResponse<Blogs[]>) => response.data);
    }

    public userLogin (credentials: Credentials): Promise<Token> {
        return this.post<string,Credentials, AxiosResponse<string>>("domain/login", credentials)
            .then(this.success);
    }

    public userRegister (user: User): Promise<number> {
        return this.post<number, User, AxiosResponse<number>>("domain/register", user)
            .then(this.success)
            .catch((error: AxiosError<Error>) => {
                throw error;
            });
    }

    public async getAllUsers (): Promise<User[]> {
        try {
            const res: AxiosResponse<User[]> = await this.get<User,AxiosResponse<User[]>>("domain/register");

            return this.success(res);
        } catch (error) {
            throw error;
        }
    }

    public getById (id: number): Promise<User> {
        return this.get<User,AxiosResponse<User>>(`domain/users/${id}`)
            .then(this.success)
    }
}

export const userApi = new UserApi(axiosConfig);

然后你创建你的axios-config.ts

import { AxiosRequestConfig } from 'axios';
import * as qs from "qs";

export const API_TIMEOUT = Number(process.env.API_TIMEOUT) || 10000;
export const API_BASE_URL = process.env.API_BASE_URL || "http://localhost:3333";

export const axiosConfig: AxiosRequestConfig = {
    withCredentials: true,
    timeout: API_TIMEOUT,
    baseURL: API_BASE_URL,
    headers: {
        common: {
            "Cache-Control": "no-cache, no-store, must-revalidate",
            Pragma: "no-cache",
            "Content-Type": "application/json",
            Accept: "application/json",
        },
    },
    paramsSerializer: (params: string) => qs.stringify(params, { indices: false }),
};

现在在 yow 组件上,您可以执行以下操作:

import {userApi} from "./UserApi";

 export default class BlogIndiv extends Component {

    constructor() {
        super();
        this.state = {
            posts: []
        };
    }

    componentDidMount() {
        const id = 1;
        return userApi.getBlogsByUiserId(id)
         .then(res=> this.setState({ posts: res }))         
   }

    render() {
        return(
            <div>
                <h1>HE</h1>
                {this.state.posts.map(e  => {
                        return (
                            <Sub title={e.title} 
                                content={e.content}
                                author={e.username}
                            />
                        )}
                    )}
            </div>
        ) 
    }
}

暂无
暂无

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

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