Can't POST through React to Rails API - ruby-on-rails

I'm trying to use fetch() to POST React form data to my Rails API, but my error within the Network tab of chrome dev tools returns:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /undefined/cars</pre>
</body>
</html>
The error in the console states the "Unexpected token '<'" indicating that my response is being sent as HTML instead of JSON, but I'm not sure why it's not converting.
Here's my fetch request:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => response.json())
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
}
Could someone please help me with this? Thanks.

Figured it out. I had to run npm i dotenv, then add a .env file to my root and add the following:
REACT_APP_API_URL=http://localhost:3001/

Related

Get Birthday Information using user.birthday.read scope

We have followed the steps mentioned as per the https://developers.google.com/identity/sign-in/web/server-side-flow. But while trying to fetch the date of birth information using 'scope': 'https://www.googleapis.com/auth/user.birthday.read', we are getting payload as below:
payload{"at_hash":"-mvIlEROpJsQSF9rQpRDfA","aud":"<CLIENT_ID>","azp":""<CLIENT_ID>"","email":"sample#gmail.com","email_verified":true,"exp":1628092721,"iat":1628089121,"iss":"https://accounts.google.com","sub":"108685651390298470023","name":"mnbvc plm","picture":"https://lh3.googleusercontent.com/a/AATXAJwejAC1r2SasgNdtqpd6f5q_Ih2-vDiTxELWDhg=s96-c","given_name":"mnbvc","family_name":"plm","locale":"en-GB"}
Please find below the index.html file we are using:
<!DOCTYPE html>
<html>
<head>
<meta name="google-signin-client_id" content="<CLIENT_ID>">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer>
</script>
<script>
function myFunction() {
auth2.grantOfflineAccess().then(signInCallback);
}
</script>
</head>
<body>
<button onclick="myFunction()" id="signinButton">Sign in with Google</button>
<script>
function renderButton() {
gapi.signin2.render('signinButton', {
'scope': 'https://www.googleapis.com/auth/user.birthday.read',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': start
});
}
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.getAuthInstance({
client_id: '<CLIENT_ID>',
scope: 'https://www.googleapis.com/auth/user.birthday.read',
access_type: 'offline'
});
});
}
function signInCallback(authResult) {
if (authResult['code']) {
var authcode = authResult['code'];
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: '/gplus.form?authcode='+authcode,
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
</body>
</html>
What else change is required at JAVA side to get the birthday information?

Token Generation for Botframework Webchat

I've been migrating my Direct Line Bot from Webchat v3 to v4.
The new version demands the use of tokens rather than the Direct Line secret in the calling page.
Here is the code (index.html) used to start the bot:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token', { method: 'POST' });
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
Question:
What code do I need to write to generate the token in other to be called by https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token ??
Realize it's got to be something like
POST https://directline.botframework.com/v3/directline/tokens/generate
Authorization: Bearer SECRET
but I don't know if it's got to be a php, js or other type of file to work.
Thanks in advance
I used php to solve this. You could give it a try.
<?php
$botSecret = '<your secret>';
$response = wp_remote_get( 'https://webchat.botframework.com/api/tokens', array( 'headers' => 'Authorization: BotConnector ' . $botSecret ) );
if( is_array($response) ) {
$header = $response['headers'];
$token = $response['body'];
}
?>
<script type="text/javascript">
var webChatToken = <?php echo $token; ?>;
</script>
I had the same issue yesterday, I just post it here in case it helps anyone in the future. If you change your code to this it should work:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token',
{ method: 'POST', headers: { Authorization: 'write your direct line secret here' }});
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
You had to add the authorization in the header of the post request to generate the token in the async function. Unfortunately this might not be obvious from Microsoft's documentation on how the generate the token
What you need to do is implement some kind of server side logic using whatever technology you're most comfortable with that uses the secret, which is kept only on your server, to generate a new token by making an HTTP request to the DirectLine channel as you point out above. Then, in your web page's start up logic, you make a request to get that token and, with the token, initialize the direct line instance in the web page. Using this approach ensures that nobody external ever gets a hold of your secret.
So, there is no one type of file to "make it work". You will need to choose Node, PHP, ASP.NET or any other server technology and implement it in the way you would any other HTTP request handler.
This article will help in understanding the authentication concepts and APIs and here's a blog post that shows how you might do it with ASP.NET and Node.

Electron - How to know when renderer window is ready

In my main process I create a renderer window:
var mainWindow = new BrowserWindow({
height: 600,
width: 800,
x: 0,
y: 0,
frame: false,
resizable: true
});
mainWindow.openDevTools();
mainWindow.loadURL('file://' + __dirname + '/renderer/index.html');
Then I want to communicate with it in some way:
mainWindow.webContents.send('message', 'hello world');
However the main window doesn't receive this message because it isn't fully done being created at the time I attempt to send it.
I have temporarily solved this by wrapping the latter code in a setTimeout() but that is most definitely not the right way to resolve a race condition.
Is there a callback for when the main window is ready? I tried the 'ready-to-show' event mentioned in the docs but it did not work.
A listener on "mainWindow" doesn't worked for me. I used instead "mainWindow.webContents".
mainWindow.webContents.once('dom-ready', () => {});
Have a look at the did-finish-load event mentioned in the Electron browser-window documentation.
mainWindow.once('did-finish-load', () => {
// Send Message
})
There seems to be a dom-ready event too.
not mentioned in the previous answers, loadURL returns a promise that resolves at the same time the 'did-finish-load' event is fired; i.e., they're essentially equivalent, except one's a promise, and the other's a callback.
Check this: https://github.com/electron/electron/blob/master/docs/api/web-contents.md
You can use this event to know if your windows is ready in you main.js [CASE 1], but if want to know when your page is full loaded you should add an event in your index.html [CASE 2] and then you can attach a function that send a message to his parent Main.js telling him, he is ready, using IPCrenderer and IPCmain
CASE 1
main.js:
mainWindows.webContents.on('did-finish-load',WindowsReady);
function WindowsReady() {
console.log('Ready');
}
CASE 2
html:
<script>
const {ipcRenderer} = require('electron');
document.addEventListener('DOMContentLoaded',pageLoaded);
function pageLoaded(){
alert('The page is loade');
ipcRenderer.send('Am_I_Ready',"Im ready");
}
</script>
Main.js:
const {ipcMain} = electron;
ipcMain.on('Am_I_Ready', doSomething)
function doSomething(){
console.log('Everything is ready.');
}
Use mainWindow.webContents like this:
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.send('message', 'hello world');
}
I tried the following code in my app
window.webContents.once("did-finish-load", () => {
console.log("did-finish-load");
});
window.webContents.once("dom-ready", () => {
console.log("dom-ready");
});
window.once("ready-to-show", () => {
console.log("ready-to-show");
});
This is after loading an index.html from local file system:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hi mom</title>
<script defer src="renderer.js"></script></head>
<body>
<div id="renderer"></div>
</body>
</html>
According to the console.log output they fired in the following sequence:
dom-ready
ready-to-show
did-finish-load
Therefore did-finish-load is probably the one to wait for -- because it's the latest therefore presumably the most-fully-loaded.
Also the API documentation for webContents.send includes this example:
// In the main process.
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})
If I remove the loading of an external script file ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hi mom</title>
<!-- <script defer src="renderer.js"></script> -->
</head>
<body>
<div id="renderer"></div>
</body>
</html>
... then the order of events is changed slightly ...
dom-ready
did-finish-load
ready-to-show
... which may explain why some of the other answers to this question contract each other.
These days, you use the "ready-to-show" event.
https://electronjs.org/docs/api/browser-window#using-ready-to-show-event

why there is meta tag in json response in laravel5

I confused very much. Please help me.
I have this java script code:
$(document).ready(function(e) {
$('#requestButton').click(function(e) {
$.ajax({
type: "POST",
dataType:"json",
data:{job:'propertyCreation' },
url: "/testajax", //Relative or absolute path to response.php file
success: function(data)
{
alert(data.responseText);
},//success
error:function(e){
alert(e.responseText);
}
}//ajax
);//ajax
});
});
Testajax function in my controller is responsible for answering to above ajax request.
public function testajax(Request $request)
{
if ($request->isMethod('post')){
$result=array('success'=>true,'response'=>$_REQUEST['job']);
return json_encode($result);
}
}
I expected that the response be
{"success":true,"response":"propertyCreation"}
but response is
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
{"success":true,"response":"propertyCreation"}
I confused why there is meta tag in json response and the result has error not success. sorry for my bad english and thank you in advance
I have tested your code in Laraver 5.2 and everything is OK.
Just one thing. According to JSON you have a little mistake in JavaScript in "alert" line:
// ...
success: function(data)
{
// Should be => alert(data.response);
alert(data.responseText);
},//success
// ...
I have multiple route files and in two route files in first of codes there was this line:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
After removing this lines, my problem was solved.
What is returned value if you console.log(data)?
FYI, you should not use json_encode to send a JSON response in Laravel. Just return $someArray and it will be automatically encoded to JSON format.

Json response is not coming while using jggrid in grails

I am using jqgrid with grails first time and facing some problem.i set up jggrid in my gsp as below
<link rel="stylesheet" href="${resource(dir:'css',file:'ui.jqgrid.css')}" />
<link rel="stylesheet" href="${resource(dir:'css/ui-lightness',file:'jquery
ui-1.8.23.custom.css')}" />
<g:javascript library="jquery-1.7.2.min"/>
<g:javascript library="jquery.jqGrid.min"/>
<script type="text/javascript">
$(document).ready(function() {
jQuery("#g-grid").jqGrid({
datatype: "json",
mtype: 'GET',
url: '${createLink(controller: 'roadmap', action: 'listRequestsAsJSON')}',
colNames: ['Entry Type', 'Life Cycle Status'],
colModel: [
{name:'roadMapEntryTypeCode',index:'roadMapEntryTypeCode', editable:'true'},
{name:'lifeCycleStatusCode',index:'lifeCycleStatusCode',editable:'true'}
],
pager: jQuery('#g-pager'),
viewrecords: true,
gridview: true
});
});
</script>
and the code in the controller for getting the response is
def listRequestsAsJSON = {
def r = AssetRoadmap.findAllByAsetIDAndRoadMapEntryTypeCode(Asset.get(10033), CodeConstants.ROADMAP_ENTRY_TYPE_CODE_LIFECYCLE, [sort:"roadMapEventStartDate", order:"asc"])
def jsonCells = r.collect {
[ id: it.id,
cell: [
it.roadMapEntryTypeCode,
it.lifeCycleStatusCode
]
]
}
def jsonData= [rows: jsonCells]
render jsonData as JSON
}
When I looked the response in Firefox (using with Firebugs) I am not seeing in it as response but when I manually render the jsp in browser I am getting
{"rows":[{"id":10172,"cell":["LIFECYCLE","DESTROY"]},{"id":10173,"cell":["LIFECYCLE","ARCHIVE"]},{"id":10174,"cell":["LIFECYCLE","CONTAINMENT"]}]}
which seem to me correct so not sure where is the problem,Any help will be greatly appreciated.Thanks!!!
The request was actually redirecting the request to some other place so the json response was not coming.I got this clue with 302 status,a good learning though

Resources