What does GET /bla - - ms - - mean in NodeJs console? - node.js

When I go to the page /bla in my NodeJS app, the console prints out
GET /bla - - ms - -
In words (for easier Google searches), dash dash ms dash dash.
What does this mean?

This is the output from morgan, a HTTP request logger middleware for node.js.
It logs all requests, by default, to the console. Depending on your configurations it will display different data from the request.
If you are using the default format (dev), the data displayed is:
:method :url :status :response-time ms - :res[content-length]

According to this thread:
The log line GET / - - ms - - is the dev format saying you never sent a response before Node.js killed the TCP connection for idling too long.
So the problem is a request that wasn't responded by the server - in other words, some middleware along the route never called next(), res.send(), res.end() or any other means to respond.
I realized that this can also occur if the server doesn't handle the client aborting the request (can be easily tested by e.g making the request through a browser and clicking on the X button in the address bar before it's done).
According to the docs, the way to handle that would probably be something like (wasn't tested):
req.on('abort', function (err) {
if (err)
console.error(error.message);
// your code here
});

Maybe its a front issue, try postman see if you have the same issue
I had the same issue , but I observed that if I use my POSTMAN, the issue never pops up, but my react app at times returns correct request but most other times there was no response and POST /story/create - - ms - - was the express log. When I looked at the code, the form submission was very weird in the front rend
<Form onSubmit={() => formTest()}>
<div
style={{ display: "flex", justifyContent: "center" }}
key={`inline-switch`}
className="mb-3"
>
{checkboxes.map((name, index) => (
<div key={index.toString()} className="mb-3">
<Form.Check
onChange={() => handleOnChange(index)}
label={name}
name="group1"
type="switch"
id={`inline-switch-${index}`}
/>
</div>
))}
</div>
<div style={{ display: "grid", placeItems: "center" }}>
<BootstrapButton
style={{ backgroundColor: "Blue", width: "48%" }}
type="submit"
>
Submit
</BootstrapButton>
and when I cleaned it up
<Form >
<div
style={{ display: "flex", justifyContent: "center" }}
key={`inline-switch`}
className="mb-3"
>
{checkboxes.map((name, index) => (
<div key={index.toString()} className="mb-3">
<Form.Check
onChange={() => handleOnChange(index)}
label={name}
name="group1"
type="switch"
id={`inline-switch-${index}`}
/>
</div>
))}
</div>
<div style={{ display: "grid", placeItems: "center" }}>
<BootstrapButton
style={{ backgroundColor: "Blue", width: "48%" }}
onClick= {() => formTest()}
>
Submit
</BootstrapButton>
The error no longer popped up. I don't know the reason nor I guarantee that this the real issue, but I suggest try to recreate by using CURL or postman or even other code like other react component's fetches. Maybe you can fix the issue

Related

Connecting Node.js with React

I am new to react and am working on my first project, I have a question on how to connect react with node.js.I have a post page where you can post data and I want to get that data in node.js so that I can connect it with MongoDB.
Here's my code
Post component
import React from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faPlus } from "#fortawesome/free-solid-svg-icons";
import "./componentStyles/postStyles.css";
const element = <FontAwesomeIcon icon={faPlus} />;
function Post() {
return (
<div>
<h2>Post your data here</h2>
<form className="post-form">
<input className="inputTitle" name="title" placeholder="Title" />
<textarea
className="inputContent"
name="content"
placeholder="Content"
rows="3"
/>
<input
className="inputTitle"
name="contact"
placeholder="contact details"
/>
<br />
<br />
<label className="inputTitle" for="CompanyType">
Company Type:{" "}
</label>
<select>
<option value="AI">AI</option>
<option value="Stocks">Stocks</option>
<option value="Finance">Finance</option>
<option value="Medical">Medical</option>
<option value="Engineering">Engineering</option>
<option value="Construction">Construction</option>
</select>
<button className="submitBtn">{element}</button>
</form>
</div>
);
}
export default Post;
Post page
import React from "react";
import Post from "../components/Post";
const Contact = () => {
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "90vh",
}}
>
<Post />
</div>
);
};
export default Contact;
Thanks in advance for Answers
There's not one "standard" way of doing this. There are several ways to do it, such as:
using redux and redux middlewares like redux-saga and redux-thunk
with hooks (react-query is worth looking at)
with a simple abstract API manager
directly inside the component (not recommended)
Anyway, React is JavaScript at the end of the day, so you need a client to make HTTP requests to the API. Many use axios.
A pseudo code example:
// APIManager.js
export const getPosts = () => {
return axios.get(`${baseUrl}/posts`).then(resp => resp.data);
};
// Post.jsx
const Post = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
APIManager.getPosts().then(res => setPosts(res));
}, []);
};
Also, there are many other client libraries that you can use for this purpose.
You need to set up a nodejs environment.
Add Express or Koa to handle requests.
Add Mongodb -> use mongo atlas and add the end point to the backend. Make sure to configure your Mongodb Atlas environment to handle requests.
Add the routes that you want to your backend to handle the data exchanges.
Use Fetch or Axios on the front end to get, post, put, delete data.
There are courses and articles that cover this more in detail. I suggest checking them out, because you will need to understand some of nuances that are specific for your use case, such as working with mongodb. This post could be turned into a book, but I just wanted to help guide you in the right direction.

form.item doesn't seem to get the validated class when entering a value in a jest test

I have a jest test to test a custom component containing the form.item from antd. I've trimmed everything down to clean out-of-the-box code to ensure this is not in my customizations.
My test file contains a defined form like this:
const TestForm = () => {
return (
<Form id='frm_test' name='frm_test'>
<Form.Item data-testid="test" label='email' name='email' rules={[{ type: 'email', message: 'test' }]}>
<Input />
</Form.Item>
</Form>
);
};
Next I have a test like this:
it('Should should validate email input', () => {
const { getByLabelText, getByTestId } = render(<TestForm />);
screen.debug(getByTestId('test'))
userEvent.type(getByLabelText('email'), 'T');
screen.debug(getByTestId('test'));
});
When I now run the test, I expect that the generated form.item will have the error message bellow the input field if you look at the debug information. This happens when you manually type something in such a situation, so I expect it to happen in the test as well. However this doesn't happen as you can see in the output from the test debug.
What I do see is that the form item is having the class ant-form-item-is-validating. I expect this to be ant-form-item-has-error (or something like that). It's as if the validation 'hangs' somewhere.
The debug information is:
<div
class="ant-row ant-form-item ant-form-item-is-validating"
data-testid="test"
>
<div
class="ant-col ant-form-item-label"
>
<label
class=""
for="frm_test_email"
title="email"
>
email
</label>
</div>
<div
class="ant-col ant-form-item-control"
>
<div
class="ant-form-item-control-input"
>
<div
class="ant-form-item-control-input-content"
>
<input
class="ant-input ant-input-sm"
id="frm_test_email"
type="text"
value="T"
/>
</div>
</div>
</div>
</div>
Okay so I saw that the validation was actually also doing a log in the console. With some messing around, I can actually do a test to see if the message appears using spy. Right now I did it with this code :
const oSpy = jest.spyOn(console, 'warn').mockImplementation();
userEvent.type(getByLabelText('email'), 'T');
expect(oSpy).toHaveBeenCalledTimes(1);
Now the above example won't reflect my message, but will work. I adjusted my custom component to contain some console.warn('some message') and then the spy can get it.
Not exactly what I wanted though. Also, I'll end up having console... in my code. I certainly don't want that when I build it. So I'll remove that with uglyfyjs.
Spend 2 days on this but i found an answer.
You can wait for the validation to end by accessing the validateFields method as follows:
const form = wrapper.find(Form);
form.props().form.setFieldsValue({
email: 'invlid email'
});
return form.props().form.validateFields().catch(err => {
expect(!!err.errorFields).toBe(true);
})

CellMeasurer support of registerChild in react-virtualized

Using the render prop registerChild as ref in CellMeasurer seems to be ignored by react-virtualized: warning findDOMNode is deprecated still received.
That comment:
https://github.com/bvaughn/react-virtualized/issues/1353#issuecomment-569814307
makes me think that the fix is 4 month old, and latest version of react-virtualized is published 6 month ago
It is already mentioned in the doc though
https://github.com/bvaughn/react-virtualized/blob/master/docs/CellMeasurer.md#using-registerchild, but erroneously:
{({registerChild}) => (
<div
style={{
...style,
height: 35,
whiteSpace: 'nowrap'
}}
>
{content}
</div>
)}
the div seems to be missing the ref={registerChild} !
Anyway, with or without ref={registerChild} on the div,
warning findDOMNode is deprecated still received
The point of registerChild is to give the cellMeasurer a ref to the child component removing the need to call findDomNode. Currently the registerChild variable isn't being used, you need to add set the ref of the child component to registerChild.
{({registerChild}) => (
<div
ref={registerChild}
style={{
...style,
height: 35,
whiteSpace: 'nowrap'
}}
>
{content}
</div>
)}

Unable to get Stripe elements to work with Vue.js

I am trying to get it so that a Vue component (currently have as just a route/view), will be able to display a styled version of Stripe Elements form for entering credit cards.
One other issue I am having is that I don't want to have the stripe js file loaded with every page like it does when in index.html. I am instead looking for it to just load on a single component/view.
My end idea is that I will have a button that when clicked will display a bootstrap modal and will show the Stripe Elements form which they then will enter their credit card info into which will, in turn, give me a token which I can then send to my backend along with an auth (JWT) header to do processing on my API.
So far I have tried mounting, creating, vue-strip-elements-plus examples and many more things.
I've included the entire Billing.vue file minus my stripe API key
I am not picky on how I do it whether it be with the way from the stripe docs or the package mentioned above.
<div class="container">
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button v-on:click="update">Submit Payment</button>
</form>
</div>
</template>
<script>
// Create a Stripe client.
var stripe = Stripe('pk_test_<key>');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {
hidePostalCode: true,
style: style
})
export default {
name: 'Billing',
data() {
},
mounted() {
card.mount('#card-element');
},
update: function() {
stripe.createToken(card).then(function(result) {
// Access the token with result.token
console.log(result.token) // I'd then send the token using axios to my backend
});
}
}
</script>```
I am expecting the token to currently be console.log which I can check in my browser

AngularJS socket.IO Bootstrap Modals only once

I have a problem with bootstrap modal window when using AngularJS together with NodeJS and socket.io. I have been googling and it seems like it is issue that has a solution, but for some reason it doesn't work when I am trying to implement it together with Socket.io. I used modals on two different places - when I click on a static div (works perfectly), when I receive a message from webSockets (opens only once and then nothing). I guess I might have a problem in my JS code since the modal when I click on a static div works fine, but I don't know.
I have an address and I am sending some data via WebSockets to the client when this link is visited. The client event looks like this:
socket.on('patient', function(data){
modalInstance = $modal.open({
templateUrl: 'templates/patient.js',
controller: 'patientModalCtrl',
resolve: {
details: function(){return data;}
}
});
});
and:
socket.on('alergy',function(data){
modalInstance = $modal.open({
templateUrl: "templates/alergy.js",
controller: 'alergyModalCtrl'
});
});
Both of these work only once and then the modal window stops to appear. Interesting is, that when I emit "alergy", then again and then "patient" I get an "alergy" window and then patient window the second "alergy" window under it.
emiting looks like this:
app.get('/api/socket/hash/:hash', function(req, res){
var hash = req.params.hash;
//allergy
if(hash === "3fDecCD"){
connected_sockets[0].emit('alergy', {alergy: true});
res.json({status: true});
}
//patient detail
else if(hash === "Vc43Sf"){
connected_sockets[0].emit('patient', {name: 'Jan', surname: 'Bjornstad'});
res.json({status: true});
}
else{
res.json({status: false});
}
});
My template looks like this:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body" style="background-color: #FFD1D1;">
<h1 style="text-align: center; color: red;">Allergy!</h1>
<h2 style="text-align: center; color: red;">The patient is allergic to opium!</h2>
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Close</button>
</div>
</div>
</div>
I am using AngularJS 1.0.7, Bootstrap CSS 2.3.1
I would say that your socket-event listeners are firing "outside of AngularJS world" and as such AngularJS machinery is not kicking-in to do its 2-way data binding "magic". In precise terms, you are not entering AngularJS $digest loop so bindings are not updated, promises not resolved etc.
The easy fix is to wrap calls to AngularJS-specific code (here - call to the $modal service) into Scope.$apply method, ex.:
socket.on('alergy',function(data){
$scope.$apply(function(){
modalInstance = $modal.open({
templateUrl: "templates/alergy.js",
controller: 'alergyModalCtrl'
});
});
});

Resources