如何使用React JS和Node JS发布REST API

时间:2019-01-04 05:53:11

标签: node.js reactjs api

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

  

http://localhost:3001/getLocaiton net :: 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")
    })

1 个答案:

答案 0 :(得分:0)

我不知道您为什么通过侦听两个端口来启动两个服务器实例,但是我注释掉了第一个端口侦听,并且您必须返回对您的/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")
})