Why Am I getting this error 'You need to enable javascript' in my React.js app? - node.js

I am getting the you need to enable javascript to run this app error in my MERN stack application. Everything else works fine except for an api call I made for a particular route. I use axios package and all API calls I made in the application are working fine and fetching required data and displayed on my browser. The problem is this particular route. This same route works fine in postman. Here is the code:
useEffect(()=>{
const fetchMenu = async () =>{
try{
const response = await axiosPrivate.get(`/api/v1/menu`, { withCredentials: true,headers:{authorization: `Bearer ${auth}`}
});
console.log(response.data, 'hello menu')
}catch(err){
}
}
fetchMenu()
}, [])
If I call the API via postman, it is fetching the data fine. AxiosPrivate is coming from axios and has been working fine in all places I used it. I really don't know what could be the problem.

The problem was with how I was calling my api. The address should have been /v1/menu instead of /api/v1/menu. This is because in my package.json file already has the proxy this way "proxy": "http://localhost:5000/api/v1",

Related

Page not changing onClick using useNavigate in React?

I have a very basic UI for a login page:
Upon clicking the LOGIN button, the following methods gets called:
async function loginPatient(){
let item ={username:userName, password};
let result = await fetch("http://localhost:8000/users/login",{
method:'POST',
headers:{
"Content-Type":"application/json",
"Accept":"application/json"
},
body: JSON.stringify(item)
});
alert(result);
alert("breakpoint")
result = await result.json();
localStorage.setItem("user-info",JSON.stringify(result));
nav('/patient')
}
At this point I simply want it to change the page when the button is clicked. My API returns the following information from the database:
To test I did console.log("hello world") in the first line of the function and it works
However, If I run console.log("hello world") after the let result = await fetch(...) part it does not work. How can I test this to see why it's not working ?
Here are the errors from the console:
I did not write the API and do not know how Node works yet, I am just doing the front end for this
The issue is code is never reaching after fetch line, basically request is failing, the error on console is saying the due to CORS issue, the request failed, and in your loginPatient function, you have not handled the failed case, if you just wrap your fetch call inside try/catch block, you will see your code will fall into fail block, as api failed.
You need to enable CORS on your server or backend, Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
You can read more about cors at:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Looks like your client is on some other domain or port(if your are developing locally) than your server. You need to enable CORS permission for your client url.
And if you are using express for your backend, you can check the following url to enable cors.
https://expressjs.com/en/resources/middleware/cors.html
And last thing why Postman is getting success response, because it is by passing this cors check, as Postman is making request from it's server to your direct server instead of browser.
First initialize you navigation variable as follows
const navigate =useNavigate()
then navigate to you specific route by returning you navigation variable as follows.
return navigation("/");
Happy Coding!

MERN Stack: Was Not Allowed to Display Insecure Content

useEffect(() => {
async function getRecords() {
const response = await fetch(`http://localhost:5000/record/`);
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
const records = await response.json();
setRecords(records);
}
Yep, Safari does not want to display mixed content...
I tried to connect the client-side React application to server-side ExpressJS & NodeJS application using MongoDB's own tutorial on their website... however I encountered this error on Javascript Console after I deployed the app on Heroku! The form retrieved from the MongoDB database does not properly show up on the website unlike its intended behaviour.
I believe that the problem can be resolved by somehow changing the URL that contains localhost to something other than that; I also tried to set the proxy address on root folder's package.JSON to http://localhost:5000 but it did not make a single change whatsoever.
Please help my fellow StackOverFlow members! Any help would be greatly appreciated!
EDIT: YOU CAN ALSO CHECK OUT THE ACTUAL WEBSITE FOR THE SAKE OF JAVASCRIPT CONSOLE... LINK

Post a simple react form - node, axios, nodemailer, backend, postman

I've set up a react form running on http://localhost:3000/about and I've the backend running on port 5000 (localhost:5000). On react's package.json I set up "proxy":"localhost:5000:.
When I use postman and I send the post to localhost:5000/api/contact, the email is sent correctly (I send the data as JSON - name, email and message). Status 200
When I use the react form, the data is well prepared as json but I can't figure out the baseURL to send correctly the method post. status 404. I tried:
localhost:3000/about/api/contact;
localhost:3000/api/contact;
localhost:3000/api.... None works...
FYI
the server is set up with the following middleware and is working ok:
app.use('/api',contactRoute)
the controller is imported and coded as following:
router.post('/contact', (req, res)=>{
const data = req.body;
The React part is not posting correctly with axios and is coded as following:
onSubmit: async (values) => {
//values.preventDefault();
try {
const data = (JSON.stringify(values, null, 2))
setLoader(true);
console.log(data)
await axios.post('/contact', data);
The method post in react is never completed, when I check the console.log of data, is correctly structured as JSON...status 404
use the post parameter in your axois request {port: 5000} then It will use your actual backend port.
By default, axios uses the base path from the URL. So, here when an API request is made.
await axios.post('/contact', data);
It is actually making the post request on localhost:3000 rather than your backend server at localhost:5000. Also, "api" should also be prepended.
One simple way is to use absolute URL which should work.
await axios.post('http://localhost:5000/api/contact', data);

React proxy not conecting to api url

when i am building a social media website, but i have run into a big problem, my api server runs on localhost:6000, and my react app runs on the default of localhost:3000, i have setup my proxy in the react app's package.json to the api url (localhost:6000), but when i make an api call using axios for example
const response = await axios.get("/api/users", body, config);
console.log(response.data);
the front end makes the api call to the localhost:300 url not my api url,
please what can i do to fix this problem it has been bugging me for the past 2 days now lol.
try setting "proxy": "127.0.0.1:6000" in your package.json file for your client.
I have 3 suggestions you could try and follow
axios.get('http://localhost:6000/api/users')
or have you tried adding this to the request?
headers: {
"accepts":"application/json"
}
and finally you could try and use this package
const { createProxyMiddleware } = require('http-proxy-middleware');
const response = await axios.get("http://localhost:6000/api/users", body, config);
console.log(response.data);
Should work, or am I missing something?

Shopify Script Tags Create method does not show response in a console

I am attempting to make a Shopify app using shopify-node-app.I have done all initial setup for making an app.I have done with setting-up App-Proxy.I have started with the Script Tag which is necessary part on making an app.I am using shopify-api-node to create ScriptTag create method and the code is below.
const registerScriptTags = function(shopDomain, accessToken, scriptTag) {
const shopName=shopDomain.replace('.myshopify.com','');
const shopify = new ShopifyAPIClient({ shopName: shopName, accessToken: accessToken });
console.log('scriptTag= ', scriptTag);
shopify.scriptTag.create({
event: 'onload',
src: 'http://yourjavascript.com/1448951127/scripttag.js'
})
.then(response => console.log(response))
.catch(err => console.error(err));
console.log('scriptTag= ', scriptTag);
}
I do not see any response , error , scriptTag in an console.
I need to Check whether I am calling this function passing the params. I am adding scriptTag as 3rd param but also hard-coding it in function.
What I needs to do here ?
1) Do I needs to hit any specific url to see the response?
2) Can anyone able to explain last two statement above with my same code ?
Thanks.
The above code was perfect.I have to stop and restart server app, unless you use nodemon which is not currently. Also I uninstall and reinstall app in demo store. Since afterAuth is called once after installation. So any code changes in afterAuth, registerWebhook, registerScriptTag will need uninstall and install.

Resources