【问题标题】:How can I POST REST API using React JS and Node JS如何使用 React JS 和 Node JS 发布 REST API
【发布时间】:2019-05-30 17:11:18
【问题描述】:

我尝试了很多次,但出现以下错误

http://localhost:3001/getLocaitonnet::ERR_CONNECTION_REFUSED 和 XMLHttpRequest.handleError 处的 createError (createError.js:17) (xhr.js:87.

我该如何解决这个问题。

axios.post ('http://localhost:3001/getLocaiton' , {
      name: keyWord,

    })  

    .then (function (response){
      console.log (response);
    })

    .catch (function (error){
      console.log (error)
    });

以下是节点后端的代码

    const express = require ('express');
    const bodyParser = require ('body-parser');
    const cors = require ('cors');
    const Client = require('node-rest-client').Client;
    const client = new Client ();
    const http = require('http')

    const app = express ();
    app.use(cors())

    app.use (bodyParser.urlencoded ({extended :false}))
    app.use(bodyParser.json());
    const server = http.createServer(app)
    server.listen(port)


    app.post ('/getLocaiton' , (req, res) =>{
        const typeWord = req.body.name;

        client.get ('https://api.adform.com/v1/help/buyer/advertisers= '+typeWord+"&key=", function (data, response){
            console.log (data);

            console.log (response);
        })
    })

    app.listen (3001, ()=> {
        console.log ("listining to port 3001")
    })

【问题讨论】:

标签: node.js reactjs api


【解决方案1】:

我不知道您为什么要通过侦听两个端口来启动两个服务器实例,但是我注释掉了第一个端口侦听并且您必须返回响应您的 /getLocaiton 请求(顺便说一下路径名称中有错字) :

const express = require ('express');
const bodyParser = require ('body-parser');
const cors = require ('cors');
const Client = require('node-rest-client').Client;
const client = new Client ();
const http = require('http')

const app = express ();
app.use(cors())

app.use (bodyParser.urlencoded ({extended :false}))
app.use(bodyParser.json());
// const server = http.createServer(app)
// server.listen(port)


app.post ('/getLocaiton' , (req, res) =>{
    const typeWord = req.body.name;
    client.get('https://api.adform.com/v1/help/buyer/advertisers='+
        typeWord+
        "&key=",function (data, response){
            console.log (data);
            console.log (response);
            // you must return your response to your request
            res.json({
                data: data
            })
        }
    )
})

app.listen (3001, ()=> {
    console.log ("listining to port 3001")
})

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-12-11
  • 2020-08-15
  • 2019-02-24
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多