there is 404 error with axios(react) and express - javascript

this is my react code
<button type='submit' onClick={()=>{axios.get('https://eccwithnodejs.df.r.appspot.com:443/user').then((res)=>{console.log(res.data)}).catch(error => {
console.log(error.response)
});}} >버튼</button>
and these are my node js code with express
this is create server code
var server=http.createServer(app).listen(8080,function(){
console.log('succesful');
})
https.createServer(options,app).listen(443,function(){
console.log('succesful https');
})
this is get method
app.get('https://eccwithnodejs.df.r.appspot.com:443/user',function(req,res){
var tempUser={"name":"asd",
"birth":970204,
"email":"으헤헤헤이거슨이메일",
"uid":"유니크다음은 전설"
}
res.send(tempUser);
console.log(tempUser);
})
and I got errorcode 404 like this
{data: '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta char…ody>\n<pre>Cannot GET /user</pre>\n</body>\n</html>\n', status: 404, statusText: '', headers: {…}, config: {…}, …}
What is the problem? please help... :(

In your get method, you also need to mention the endpoint not full domain name. So, remove your domain name from the get method.
app.get(/user',function(req,res){
var tempUser={"name":"asd",
"birth":970204,
"email":"으헤헤헤이거슨이메일",
"uid":"유니크다음은 전설"
}
now change your react code.
<button type='submit' onClick={()=>{axios.get('https://<<your_domain>>:8080/user').then((res)=>{console.log(res.data)}).catch(error => {
console.log(error.response)
});}} >버튼</button>

Related

Axios get call in Vue3 not working, although curl and javascript work as expected

I'm trying to make an API call from my Vue3 app. The prepared API has an endpoint like http://localhost:8888/api/dtconfigsearch, where one needs to pass a json payload like { "Modelname": "MyFancyModel"} to get the full dataset with the given modelname. Pure get functions without a payload / a body do work from my Vue3 project to the golang backend, but I'm having problems with passing a payload to the backend.
Test with curl -> ok
$ curl -XGET localhost:8888/api/dtconfigsearch -d '{"Modelname" : "MyFancyModel" }'
{"ID":4,"Modelname":"MyFancyModel","ModelId":"96ee6e80-8d4a-b59a-3524-ced3187ce7144000","OutputTopic":"json/fancyoutput"}
$
This is the expected output.
Test with javascript ok
Source file index.js:
const axios = require('axios');
function makeGetRequest() {
axios.get(
'http://localhost:8888/api/dtconfigsearch',
{
data: { Modelname : "MyFancyModel" },
headers: {
'Content-type' : 'application/json'
}
}
)
.then(resp => {
console.log(resp.data)
})
.catch(err => {
console.log(err)
})
}
makeGetRequest()
Output
$ node index.js
{
ID: 4,
Modelname: 'MyFancyModel',
ModelId: '96ee6e80-8d4a-b59a-3524-ced3187ce7144000',
OutputTopic: 'json/fancyoutput'
}
$
Here, I also get the desired output.
Test within Vue fails :-(
Source in the Vue one file component:
onSelection(event) {
let searchPattern = { Modelname : event.target.value }
console.log(event.target.value)
console.log("searchPattern = " + searchPattern)
axios.get("http://localhost:8888/api/dtconfigsearch",
{
data : { Modelname : "Windshield"},
headers: {
'Content-type' : 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
.then(response => {
console.log(response.data)
})
.catch(err => {
console.log(err)
alert("Model with name " + event.target.value + " not found in database")
})
},
Output in browser:
In the image you can see in the terminal log on the right side that the backend is not receiving the body of the API call. However, in the browser information of the call there is content in the config.data part of the object tree, which is the payload / the body. The only thing that bothers me that it is not a json object, but stringified json, although it was entered as json object. According to the documentation, the parameter name (data) in the call should be correct to hold the body content of the api call.
I've tried different header information, looked if it could be a CORS issue, what it isn't to my opinion, exchanged key data with body, used axios instead of axios.get and adapted parameter, all without success. The version of the axios library is 0.27, identical for Vue and vanilla javascript. After checking successfully in javascript, I was sure that it would work the same way in Vue, but it didn't.
Now I'm lost and have no further ideas how to make it work. Maybe someone of you had similar issues and could give me a hint? I'd be very grateful for some tipps!!

CORS No 'Access-Control-Allow-Origin' error in React app w/ Facebook

I'm a junior developer that's fairly new to using Facebook for Developers. I'm hitting a wall with the ReactJs application I'm building and could use your help!
My boss has requested a Grid representation of the Page Plugin, not the actual Plugin itself. For this project, he's requested I make and use a test 'Page' I've found that DevExtreme's Data Grid seems to be the best option in terms of the desired visual, and I'm trying to call my Facebook Page using the Graph API documentation. I know it's hitting at least the area I want it to with my console.log because it's returning the error message.
Here are the errors my browser is returning:
Access to fetch at 'https://www.facebook.com/Feeds-Tester-170107151801959/' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET https://www.facebook.com/Feeds-Tester-170107151801959/ net::ERR_FAILED
The link you'll see referenced in my URL variable has been triple checked to be the correct link. Since I'm using NodeJS, I tried installing the CORS npm package but I'm not 100% sure where to put it to use it, I'm wondering if that's the cause of the issue?
Here's my full code snippet (I'm using VS Code, if that helps):
/*global FB*/
import React from 'react';
import { DataGrid, Editing, Scrolling, Lookup, Summary, TotalItem } from 'devextreme-react/data-grid';
import { Button } from 'devextreme-react/button';
import { SelectBox } from 'devextreme-react/select-box';
import CustomStore from 'devextreme/data/custom_store';
import { formatDate } from 'devextreme/localization';
import 'whatwg-fetch';
const URL = 'https://www.facebook.com/Feeds-Tester-170107151801959/';
const REFRESH_MODES = ['full', 'reshape', 'repaint'];
class Grid extends React.Component {
constructor(props) {
super(props);
this.state = {
fbData: null,
ordersData: new CustomStore({
key: 'OrderID',
load: () => this.sendRequest(`${URL}`, 'GET'),
}),
requests: [],
refreshMode: 'reshape'
};
this.clearRequests = this.clearRequests.bind(this);
this.handleRefreshModeChange = this.handleRefreshModeChange.bind(this);
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Post ID: ' + response.id);
}
})
}
sendRequest(url, method, data) {
method = method || 'GET';
data = data || {};
this.logRequest(method, url, data);
if(method === 'GET') {
return fetch(url, {
method: method,
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
}
}).then(result => result.json().then(json => {
if(result.ok) return json.data;
throw json.Message;
}));
}
const params = Object.keys(data).map((key) => {
return `${encodeURIComponent(key) }=${ encodeURIComponent(data[key])}`;
}).join('&');
return fetch(url, {
method: method,
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
credentials: 'include'
}).then(result => {
if(result.ok) {
return result.text().then(text => text && JSON.parse(text));
} else {
return result.json().then(json => {
throw json.Message;
});
}
});
}
logRequest(method, url, data) {
const args = Object.keys(data || {}).map(function(key) {
return `${key }=${ data[key]}`;
}).join(' ');
const time = formatDate(new Date(), 'HH:mm:ss');
const request = [time, method, url.slice(URL.length), args].join(' ');
this.setState((state) => {
return { requests: [request].concat(state.requests) };
});
}
clearRequests() {
this.setState({ requests: [] });
}
handleRefreshModeChange(e) {
this.setState({ refreshMode: e.value });
}
render() {
const { refreshMode, ordersData } = this.state;
return (
<React.Fragment>
<DataGrid
id="grid"
showBorders={true}
dataSource={ordersData}
repaintChangesOnly={true}
>
<Editing
refreshMode={refreshMode}
mode="cell"
allowAdding={true}
allowDeleting={true}
allowUpdating={true}
/>
<Scrolling
mode="virtual"
/>
<Lookup dataSource={ordersData} valueExpr="Value" displayExpr="Text" />
<Summary>
{/* <TotalItem column="CustomerID" summaryType="count" />
<TotalItem column="Freight" summaryType="sum" valueFormat="#0.00" /> */}
</Summary>
</DataGrid>
<div className="options">
<div className="caption">Options</div>
<div className="option">
<span>Refresh Mode: </span>
<SelectBox
value={refreshMode}
items={REFRESH_MODES}
onValueChanged={this.handleRefreshModeChange}
/>
</div>
<div id="requests">
<div>
<div className="caption">Network Requests</div>
<Button id="clear" text="Clear" onClick={this.clearRequests} />
</div>
<ul>
{this.state.requests.map((request, index) => <li key={index}>{request}</li>)}
</ul>
</div>
</div>
</React.Fragment>
);
}
}
export default Grid;
This is the link to the docs for the module I'm trying to reference
I'm trying to not bite off more than I can chew and just start with retrieving the data before I even think about manipulating it or sending any in return. Any insight or guidance you can provide would be greatly appreciated. Thank you!! :)
Do not use fetch with the Facebook URL, it won't let it happen on the browser, instead, use the Facebook API for everything you need to do with it
For example, instead of fetching the page, use the api with the page
FB.api('/Feeds-Tester-170107151801959', function(response) {
// ...
});
If you need to fetch the page, then you have to do it outside the browser environment or use a proxy like cors anywhere, but you can avoid that by using the Facebook API
I was also getting these error. I found that the pageId, I was using was wrong🤦‍♀️. These errors come only when your pageId is wrong or the domain is not whitelisted properly(I even tried with a ngrok url and it worked😵).
So the steps which I followed were:
In buisness.facebook.com go to inbox from sidebar and select chat plugin. [https://i.stack.imgur.com/rDk5d.png]
Click on setup to add your domain. [https://i.stack.imgur.com/exOi2.png]
Pick a setup method(standard for react/nextjs) and setup chat plugin(add language, domain, copy code and paste it). [https://i.stack.imgur.com/hDArZ.png]
You can add multiple domains. [https://i.stack.imgur.com/zGdgx.png]
You will get pageId already embedded. [https://i.stack.imgur.com/iRT13.png]
Use this code and paste it in _document.js file in nextjs. and after deploying it will work perfectly. For any confusion please let me know. Thanks, Happy Coding ☺

400 Bad Request issue with POST request from my Vue app to my Rails API

I'm learning Rails and Vue, and created a simple Rails API and Vue app to learn how to GET and POST from my Vue app to my Rails API. So far the GET requests are fine but I'm getting 400 Bad Request due to bad syntax from sending POST requests. The POST requests work when testing it using Insomnia (an API testing app similar to Postman), but I get 400 when I use my Vue app to POST.
Here's my Rails controller:
def create
#todo = Todo.new(todo_params)
if #todo.save
render :show, status: :created, location: #todo
else
render json: #todo.errors, status: :unprocessable_entity
end
end
...
private
def set_todo
#todo = Todo.find(params[:id])
end
def todo_params
params.require(:todo).permit(:title, :description, :finished)
end
Here's my Vue app, with a simple text input to POST to my Rails:
<template>
<input type="text" v-model="postBody"/>
<button v-on:click="submit()">Submit</button>
</template>
<script>
import axios from 'axios';
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
todos: [],
errors: [],
postBody: ''
}
},
methods: {
submit() {axios.post(`http://localhost:3000/todos/`, {
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(this.postBody)
})
.then(response => response.data)
.catch(e => {
this.errors.push(e)
})
}
}
}
</script>
I try to submit this POST request in JSON into the text input to my Rails endpoint http://localhost:3000/todos/:
{
"title": "Sweets",
"description": "Buy cookies",
"finished": false
}
Then I get this error from the browser:
{status: 400, error: "Bad Request",…}
error: "Bad Request"
exception: "#<ActionController::ParameterMissing: param is missing or the value is empty: todo>"
status: 400
traces: {Application Trace: [{id: 1, trace: "app/controllers/todos_controller.rb:51:in `todo_params'"},…],…}
Application Trace: [{id: 1, trace: "app/controllers/todos_controller.rb:51:in `todo_params'"},…]
0: {id: 1, trace: "app/controllers/todos_controller.rb:51:in `todo_params'"}
1: {id: 2, trace: "app/controllers/todos_controller.rb:24:in `create'"}
This is the error I'm getting from terminal from my local Rails server (I'm testing this in local environment in both Vue and Rails):
Started POST "/todos/" for ::1 at 2020-09-21 12:09:16 +0800
Processing by TodosController#create as JSON
Parameters: {"headers"=>{"Content-Type"=>"application/json; charset=UTF-8"}, "body"=>"\"{ \\\"title\\\": \\\"Sweets\\\", \\t\\\"description\\\": \\\"Buy cookies\\\", \\\"finished\\\": false }\"", "todo"=>{}}
Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms)
ActionController::ParameterMissing (param is missing or the value is empty: todo):
app/controllers/todos_controller.rb:51:in `todo_params'
app/controllers/todos_controller.rb:24:in `create'
I understand it might be something to do with strong params in my Rails controller, so when I removed the required params .require(:todo) the POST went through but the JSON fields are all null.
{
"id": 6,
"title": null,
"description": null,
"finished": null
}
I also tried to see if it was related to how the form data in my Vue app was sent to my Rails endpoint, so I tried JSON.stringify on the body but it didn't help.
This is Day 3 of me trying to solve this, without success. What did I do wrong? Any help much appreciated! :)
Firstly, you are submitting the title, description etc on the root of the JSON payload, but Rails is expecting them nested under todo.
Secondly, you are submitting the headers in the payload argument of the axios request - the first argument to post is the payload, the second argument is the configuration.
Thirdly, you shouldn't need to convert your data to a JSON string yet. axios should handle that for you.
Try this axios request instead:
axios.post(
`http://localhost:3000/todos/`,
{ todo: this.postBody },
{ headers: { 'Content-Type': 'application/json; charset=UTF-8' }
)
After going down the rabbit hole of various error messages from Rails console, I realised it's nothing to do with the Rails API or the strong params, but how I structure the inputs to not POST a malformed JSON to my Rails endpoint. Reading the npm axios documentation helped loads.
So instead of a single text input field in my Vue app, I created a form with matching field names to my params:
<form #submit.prevent="onSubmit">
<div class="input">
<label for="title">Title</label>
<input
type="text"
id="title"
v-model="title">
</div>
<div class="input">
<label for="name">Description</label>
<input
type="text"
id="description"
v-model="description">
</div>
<div class="input">
<label for="finished">Finished?</label>
<input
type="text"
id="finished"
v-model="finished">
</div>
<div class="submit">
<button type="submit">Submit</button>
</div>
</form>
And then in my methods:
methods: {
onSubmit() {
const formData = {
title: this.title,
description: this.description,
finished: this.finished
}
axios({
method: "POST",
url: "http://localhost:3000/todos/",
headers: {"Content-Type": "application/json"},
data: formData
})
.then(response => {
console.log(response);
})
.catch(e => {
this.errors.push(e)
})
},
And that did the trick! I can POST to my Rails API now. The problem for me is I still don't understand how and why it worked, other than it did! So any answers appreciated just for personal learning (but not critical to the original problem).

Service ID invalid when trying to use EmailJS with React

I created a form to contact me on my website, for that I use EmailJS.
However when I try to send myself a mail through the contact form I got a 400 Error The service ID is invalid.
I followed every steps of that tutorial as I haven't use EmailJS before https://blog.mailtrap.io/react-send-email/
Here is my Contact component
class Contact extends React.Component {
constructor(props) {
super(props);
this.state = { feedback: '', name: 'Name', email: 'email#example.com' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<form className="test-mailing">
<h1>Let's see if it works</h1>
<div>
<textarea
id="test-mailing"
name="test-mailing"
onChange={this.handleChange}
placeholder="Post some lorem ipsum here"
required
value={this.state.feedback}
style={{width: '100%', height: '150px'}}
/>
</div>
<input type="button" value="Submit" className="btn btn--submit" onClick={this.handleSubmit} />
</form>
)
}
handleChange(event) {
this.setState({feedback: event.target.value})
}
handleSubmit() {
const templateId = 'template_id';
this.sendFeedback(templateId, {message_html: this.state.feedback, from_name: this.state.name, reply_to: this.state.email})
}
sendFeedback (templateId, variables) {
window.emailjs.send(
'gmail', templateId,
variables
).then(res => {
console.log('Email successfully sent!')
})
// Handle errors here however you like, or use a React error boundary
.catch(err => console.error('Oh well, you failed. Here some thoughts on the error that occured:', err))
}
}
And here is what I added in my index.html
`<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/emailjs-com#2.3.2/dist/email.min.js"></script>
<script type="text/javascript">
(function(){
emailjs.init("my_user_ID_here"); // Obtain your user ID at the dashboard https://dashboard.emailjs.com/integration
})();
`
To fix this, I had to swap out 'gmail' with my service ID.
sendFeedback (templateId, variables) {
window.emailjs.send(
***serviceID here***, templateId,
variables
).then(res => {
console.log('Email successfully sent!')
})
// Handle errors here however you like, or use a React error boundary
.catch(err => console.error('Oh well, you failed. Here some thoughts on the error that occured:', err))
}
The JavaScript console in my web browser helped identify this.
That was happening to me, and it was because I didn't have the account activated.
when you log in, click on 'email services' and select, for example, gmail with your account
pd: google translate
Had the same problem.
To fix it,
I had to paste NOT the 'gmail' string itself but the service_id which
is below the icon gmail
in the EmailJS website after log in. Everyone has its own specific number. Also the template_id is important to put the id generated for your template.
When you want to publish your project it is advisable to place your special ids to the .env file to stay secure.
Please try to check whether you are using the right integration id, check the id token you are using with the one under integration id on the dashboard, this was my issue
Might as well share a quick fix that would probably save someone's time. I just had the same issue while using the code below.
const notifyOwnerOfGuest = async () => {
const userId = 'user_...';
const serviceId = 'service_...';
const templateId = 'template_...';
const accessToken = 'e2e1...';
const postfields = {
user_id: userId,
service_id: serviceId,
template_id: templateId,
accessToken,
};
const response = await fetch('https://api.emailjs.com/api/v1.0/email/send', {
method: 'POST',
body: JSON.stringify(postfields),
// should explicitly add the header content-type here
});
if (!response.ok) throw await response.text();
};
I just explicitly added a Content-type header like so
headers: {
'Content-Type': 'application/json',
},
and now it works.

Google oauth satellizer 404 Error

This is my code. I am using authenticate('google'). After clicking on allow button I get error 404.
I am using satellizer.js for google authentication.
Please help me if you understand this error.
Error in browser
POST http://localhost:8080/auth/google 404 (Not Found)
Object {data: "Cannot POST /auth/google↵", status: 404, config: Object, statusText: "Not Found"}
Inside controller
$scope.authenticate = function (provider) {
$auth.link(provider)
.then(function(response) {
// You have successfully linked an account.
console.log(response);
})
.catch(function(response) {
// Handle errors here.
console.log('----------error--------')
console.log(response);
});
};
My code inside app.js
$authProvider.google({
clientId: 'xxxxxxxxxx2op4madn.apps.googleusercontent.com'
});
$authProvider.google({
url: '/auth/google',
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
requiredUrlParams: ['scope'],
optionalUrlParams: ['display'],
scope: ['profile', 'email'],
scopePrefix: 'openid',
scopeDelimiter: ' ',
display: 'popup',
type: '2.0',
popupOptions: {width: 452, height: 633}
});
I got the issue actually it's find a post request on that URL you can add some configuration inside you server.js file follow this given GIT-URL.
github satellizer

Categories

Resources