React web application proxy - node.js

I am creating a simple web application. I have a problem, in the App.js file I have a function called Submit which calls a POST function with AXIOS when i press a button
componentDidMount() {
axios.get("/get")
.then((response) => {
this.setState({
fetchData: response.data
})
})
//this.Get().then((response)=>{ console.log("sono qui")})
}
submit = () => {
axios.post(`/insert`, this.state)
.then(() => { alert('success post') })
console.log(this.state)
document.location.reload()
}
I have another file called setupProxy.js where I direct these calls to the server
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware('/get', { target: "http://localhost:3001" }));
app.use(createProxyMiddleware('/insert', { target: "http://localhost:3001"}));
};
The problem is that the server fails to enter the POST call while the GET call manages to enter quietly. Where am I wrong?
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.post('/insert',(req,res)=>{
console.log(req.body.setBookName);
let options = {
url: 'http://backend.default.svc.cluster.local',
form: {
setBookName:this.state.setBookName ,
setReview: this.state.setReview
}
};
request.post(options);
})
app.get('/get',(req,res)=>{
console.log("Entro");
request.get("http://get-server.default.svc.cluster.local").pipe(res);
})
app.listen('3001', () => {console.log("Listening") })

The app.post code doesn't generate a response for the client.
request.post(options);
Maybe you need to pipe the response like the .get request?
request.post(options).pipe(res);

Related

TestCafe Triggering Test By POST Request In Express

I had a question that doesn't seem to be answered anywhere.
I am running tests from within my Express.js api. I set up a page that has a button and a field to enter a keyword intended to be used during a testcafe test. My endpoint I set up is /testcafe. But after sending a post request to /testcafe, there is a long delay while test runs and so my question is what is the best next step besides hanging?
Also, can my post request body, which contains the keyword, be directly used in a test like this? Keep in mind it's this pattern:
frontend -> POST request -> Express server -> /testcafe endpoint - test
My problem is after it reaches test, I currently have it attempting to call fetch from within the request logger. Is this right?
import { ClientFunction, Selector } from 'testcafe';
import { RequestLogger, RequestHook } from 'testcafe';
import zlib from 'zlib';
import fetch from 'isomorphic-unfetch';
const url = 'https://www.mysitetesturl.com/page';
class MyRequestHook extends RequestHook {
constructor (requestFilterRules, responseEventConfigureOpts) {
super(requestFilterRules, responseEventConfigureOpts);
}
onRequest (e) {
console.log('in onRequest!')
console.log('========================')
console.log('Request Body')
let buf = e._requestContext.reqBody
console.log(buf.toLocaleString())
}
onResponse (e) {
let buf = Buffer(e.body)
let unzippedBody = Buffer(zlib.gunzipSync(buf))
let payload = unzippedBody.toLocaleString()
fetch('http://myapiipaddress/api/testcafe',
method: 'PUT',
body: JSON.stringify(payload)
)
.then((err, doc) => {
if(err) {
console.log(err)
} else {
console.log(doc)
}
})
}
}
const myRequestHook = new MyRequestHook({
url: url,
method:'get'},
{
includeHeaders: true,
includeBody: true
}
);
fetch('http://myapiipaddress/api/testcafe',
method: 'GET'
)
.then((err, doc) => {
if(err) {
console.log(err)
} else {
fixture`myfixture`
.page(doc.url)
.requestHooks(myRequestHook);
test(`mytest`, async t => {
const inputField = Selector('input');
await t
await t
.wait(5000)
.typeText(inputField, doc.text)
.wait(5000)
}
);
}
})
According to your scheme, you need to organize your code in a different way:
const createTestCafe = require('testcafe');
....
// Choose the necessary body parser for express application
// https://github.com/expressjs/body-parser
app.use(bodyParser.urlencoded({ extended: true }));
...
app.post('/', function (req, res) {
createTestCafe('localhost', 1337, 1338, void 0, true)
.then(testcafe => {
const runner = testcafe.createRunner();
return runner
.src('/tests')
.browsers('chrome')
.run();
})
.then(failedCount => {
testcafe.close();
res.end();
});
})

why is axios fetch not working on mobile?

I have the following setup which works on my PC but doesn't on mobile even when there is data to fetch.
useEffect(() => {
const {username, room} = queryString.parse(location.search);
setRoom(room);
if (messages.length > 3) {
let lastMessage = messages.pop();
setMessss([lastMessage]);
const fetchHistory = async () => {
try {
const result = await axios.get(`https://example.com/messages/${room}`,);
setMessss(result.data.messagesFromAPI);
} catch (error) {
console.log(error);
}
};
fetchHistory();
}
}, [messages]);
I also have another useEffect hook that works on PC on componentDidMount but doesn't work if I reload the page more than once but I want it to work on every page reload but it doesn't fetch...
could this be because I use the free subscription (M0) on Mongodb Atlas? Although from metrics my database hasn't exhausted or reached capacity.
useEffect(() => {
const {username, room} = queryString.parse(location.search);
// setRoom(room);
axios.get(`https://example.com/messages/${room}`)
.then(response => {
const history = response.data.messagesFromAPI;
setMessss(history);
})
.catch(error => {
console.log(error.response);
});
},[]);
Here's how I solved it
In the src folder just add a file called
setupProxy.js
and write this code inside
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
["/api/*",], // the base api route you can change it
createProxyMiddleware({
target: "http://localhost:4000", // the local server endpoint
})
);
};
make sure to change the target port to the port where the server is running.
For some reason axios does not behave properly locally.
You can add the setupProxy.js to .gitignore

React app on Heroku cannot make a POST request

I+m playing with the Chatkit API, and when running a React app in my local machine everything seems to work fine, but when I pushed it to Heroku, every time it tries to do a POST request through the server, it gives Failed to load resource: net::ERR_CONNECTION_REFUSED and index.js:1375 error TypeError: Failed to fetch
This is my server.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const Chatkit = require('#pusher/chatkit-server')
const app = express()
const chatkit = new Chatkit.default({
instanceLocator: I HAVE MY INSTANCE LOCATOR HERE,
key: I HAVE MY KEY HERE,
})
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())
app.post('/users', (req, res) => {
const { username } = req.body
chatkit
.createUser({
id: username,
name: username
})
.then(() => res.sendStatus(201))
.catch(error => {
if (error.error === 'services/chatkit/user_already_exists') {
res.sendStatus(200)
} else {
res.status(error.status).json(error)
}
})
})
app.post('/authenticate', (req, res) => {
const authData = chatkit.authenticate({ userId: req.query.user_id })
res.status(authData.status).send(authData.body)
})
const PORT = 3001
app.listen(PORT, err => {
if (err) {
console.error(err)
} else {
console.log(`Running on port ${PORT}`)
}
})
And then this is my App.js
import React, { Component } from 'react'
import UsernameForm from './components/UsernameForm'
import ChatScreen from './ChatScreen'
class App extends Component {
constructor() {
super()
this.state = {
currentUsername: '',
currentScreen: 'WhatIsYourUsernameScreen'
}
this.onUsernameSubmitted = this.onUsernameSubmitted.bind(this)
}
onUsernameSubmitted(username) {
fetch('http://localhost:3001/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username }),
})
.then(response => {
this.setState({
currentUsername: username,
currentScreen: 'ChatScreen'
})
})
.catch(error => console.error('error', error))
}
render() {
if (this.state.currentScreen === 'WhatIsYourUsernameScreen') {
return <UsernameForm onSubmit={this.onUsernameSubmitted} />
}
if (this.state.currentScreen === 'ChatScreen') {
return <ChatScreen currentUsername={this.state.currentUsername} />
}
}
}
export default App
I believe that it's at this time that it breaks
return <UsernameForm onSubmit={this.onUsernameSubmitted} />
When submitting it is expected to make a POST request to create a new user, and React to load the new component, but it just stays in the UsernameForm component, and in the console I can see these errors:
Failed to load resource: net::ERR_CONNECTION_REFUSED
index.js:1375 error TypeError: Failed to fetch
Probably the issue is the localhost in the endpoint at onUsernameSubmitted. We need more details about how your application is deployed and how the communication between server and spa is designed. If you have an Nginx you can set the redirect there.
I see three potential reasons of the error:
Database has to be well deployed and db:migrate triggered to define the db schema.
If 1) is fulfilled, then make sure whether your graphql path points to server url my-app.herokuapp.com not to localhost:<port>, The easiest way to check that is via browser/devtools/network query.
(optional) I use ApolloClient and my rule process?.env?.NODE_ENV ? 'prod_url' : 'dev_url' didn't work because of missing vars definitions in webpack:
new DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),```

ctx request body is undefined with nodejs

I have a problem, when I post my form, i can't get what is in my post in my API.
this is my post with axios in react :
onSubmit = () => {
let data = {
nickname: this.state.nickname,
password: this.state.password
}
axios.post("/api/user/login", { data })
.then(res => {
console.log("res from api is => ", res.data);
})
}
and this is in my API :
import koaBody from "koa-body";
const app = new koa();
const router = new Router();
app.use(router.routes());
app.use(koaBody());
router.post("/api/user/login", async(ctx) => {
console.log("body is => ", ctx.request.body);
ctx.body = "ok";
});
the problem is ctx.request.body is always undefined...
Can you tell me why ?
I tried with router.get and I have no problem, it works fine.
You need to load the body parser before the router, otherwise the router will get to handle the requests before the body contents are parsed:
app.use(koaBody());
app.use(router.routes());

Indexing user query with Appbaseio and ReactiveSearch

I'm attempting to index a user's query using ReactiveSearch's DataSearch component and appbase-js.
So I've made my Node/Express app for appbase-js interaction with appbaseio.
in app.js:
...
const search = require('./routes/search');
...
app.use('/api/search', search);
Then here is my search.js
const express = require('express');
const Appbase = require('appbase-js');
// create an appbase.io app's instance
const appbaseRef = new Appbase({
url: "https://scalr.api.appbase.io",
app: "index-query",
credentials: "####-####"
});
const router = express.Router();
/* GET search. */
router.get('/test', (req, res, next) => {
res.send('This is the SEARCH route - and it WORKS!');
});
router.post('/query', (req, res, next) => {
appbaseRef.index({
type: "autocomplete",
body: value
}).then('data', response => {
console.log("#index success: ", response);
}),('error', error => {
console.log("#index error: ", error);
});
});
module.exports = router;
Then here is my DataSearch component:
<DataSearch
componentId="SearchSensor"
dataField={["suggestions"]}
className="search-bar"
iconPosition="right"
innerclassName={{
list: "text-item"
}}
onValueSelected{
(value) => {
????
}
}
/>
I was advised in another question not do this:
onValueSelected={(value) => {
fetch('YOUR_SERVER_URL' or 'Elasticsearch URL', { method: 'POST', body: {...} })
}
So as not to expose sensitive information on the client
I'm not sure how to get value (the user's query) from my React front end to my Node/Express backend so that it can be indexed to ES app on Appbaseio?
Say your server is hosted at 'SERVER_URL', the key is to send the data from the frontend to the server via a fetch request:
<DataSearch
...
onValueSelected={(value) => {
fetch('SERVER_URL/api/search/query', {
method: 'POST',
body: JSON.stringify({ value })
}).then(() => handle response client side))
}}
/>
Then you can add the body-parser middleware in express.
app.use(bodyParser.json())
In your route you can use the value from body and index it to elasticsearch. You can use the index method from appbase-js which you're using here.
router.post('/query', (req, res, next) => {
appbaseRef.index({
type: "autocomplete",
body: { value: req.body.value }
}).then('data', response => {
console.log("#index success: ", response);
}),('error', error => {
console.log("#index error: ", error);
});
});

Resources