簡體   English   中英

React-使用axios的Nodejs / Express獲取請求-無法從客戶端訪問我的后端路由-有什么錯誤?

[英]React - Nodejs / express get request using axios - can't hit my backend route from client - what is the mistake?

我正在嘗試從后端路由發出api請求(使用node / express)。 從客戶端站點,我正在發出axios請求並使用react。 我測試了我的快速后端路由,它工作得很好,所以問題必須出在我的客戶端代碼上。 我已經看了一段時間了,不知道我做錯了什么,任何幫助都將是很大的! 謝謝!

我的后端節點快遞路線:

 router.get('/testing', function(req,res){
        sampleAPI.get('example/?origin=' + req.query.city + '&name=' + req.query.name + '&xxx=yes&yyy=no&xyx=maybe', function(err, data){
                  if (err){
                     res.status(200).send(err);
                  }
                  else{
                     res.status(200).send(data);
                  }
         })
 })

api請求:

     export function search (city, name) {
            return axios.get('api/testing', {
                params: {
                    city: city,
                    name:name
                }
     })

反應成分:

        import React from 'react';
        import {search} from '../api.js';
        class Searching extends React.Component {
            constructor(props){
                super(props);
                this.state={
                    city:'',
                    name:''
                }
                this.handleInput=this.handleInput.bind(this);
                this.testing=this.testing.bind(this);
            }
            testing(e){
                this.setState({
                    [e.target.name]:e.target.value
                })
            }

            handleInput(e){
                e.preventDefault();
                search(this.state.city, this.state.name)
            }
            render () {
                return (
                    <div>
                      <form onSubmit={this.handleInput}>
                         <input type="text" name="city"  value={this.state.city} onChange={this.testing} />
                         <input type="text"  name="name" value={this.state.name} onChange={this.testing}/>
                         <input type="submit" value="Submit" />
                       </form>
                    </div>
                 )
            }
        }

        export default Searching;

在axios請求中,您的目標是'api/testing'的終結點。 您定位的快速路由器路由為'/testing' ,因此您在該路由器文件中的某個位置將'/testing'端點嵌套在'/ api'路由內,例如router.use('/api', require('./api'));

此axios請求是否有效:

export function search (city, name) {
   return axios.get(`/api/testing/${city}/${name}`);
}

使用此端點:

router.get('/testing/:city/:name', function(req,res){
    sampleAPI.get('example/?origin=' + req.params.city + '&name=' + req.params.name + '&xxx=yes&yyy=no&xyx=maybe', function(err, data){
        if (err){
           res.status(200).send(err);
        }
        else {
           res.status(200).send(data);
        }
     })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM