简体   繁体   中英

Need help to create the server.js to work around the CORS issue

So, I need to hit an API and render the response in a html element. I have my app.js doing this:

let url = 'http://localhost:80/db/abc/query/';

class abc extends Component {
state {userinput:""}

getResponse = () => {
        axios.get(url+this.state.userinput, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            this.setState({results: response.data})
        });
 }

render () { //ignore the render for now
   return ()
}
}
export default abc;

But since I was getting the CORS error, I created a server.js & started the proxy using # node server.js command. But for some reason I keep getting Error 500 back from the API.

Server.js

var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use('/', function(req, res) {
    var url = 'https://' +
      req.get('url').replace('localhost:80', 'my-real-host-fqdn:8122') + 
      req.url
    req.pipe(request({ qs:req.query, uri: url })).pipe(res);
  })

app.listen(80, function () {
    console.log('CORS-enabled web server listening on port 80')
    })

I call my getResponse() on a button click, which is working but not included in the excerpt above.

Error Messages:

GET http://localhost/db/abc/query/<userinput> 500 (Internal Server Error)
createError.js:17 Uncaught (in promise) Error: Request failed with status code 500

Errors with proxy server:

CORS-enabled web server listening on port 80
TypeError: Cannot read property 'replace' of undefined

OR

CORS-enabled web server listening on port 80
ReferenceError: request is not defined

I am not very familiar with the server.js file and using express. How does this work, and have I made any mistakes here?

So what did the trick for me was removing this line from my server.js:

 req.pipe(request({ qs:req.query, uri: url })).pipe(res);

Posting this here so it helps someone with a similar issue. Thanks for trying to help guys!!

to get host, use req.get('host'). Seems like req.get('url') is the issue.

app.get('/one/two', function (req, res) {
    var url = req.url;
}

How to get the full url in Express?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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