Using Fetch in react, need username password to access database











up vote
2
down vote

favorite












I have done hours of research on this and just can't find the answer I need. Sorry if this has been asked and I have been bad in my research, if so just link the helpful stack overflow page and I'll be on my merry way. Here is the summary of my problem.



I am in a CS4 class and we are designing our own webpage and must use our school's server for database storage. We learned php and how to use mySQL and our POST and GET requests for the server would look like this (written in PHP):



require("config.php");

$db = new PDO("mysql:dbname=" . $GLOBALS["database"] . ";host=" . $GLOBALS["hostname"] . ";port=" . $GLOBALS["port"],
$GLOBALS["username"], $GLOBALS["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT * FROM Karrsen_ajaxtest";
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetchAll();
foreach ($rows as $row) {
print(strip_tags($row['name']) . "<br/>");
}


Where the config was set correctly.



Now I am doing my final project it React.js and have to request from the same server. I want to use the built in Fetch system but it throws CORS errors and I also don't know how to add the aforementioned username, password, database, and hostname. I have looked through the MDN webdocs thoroughly (thought it might be request Header, Credentials, Mode, or Integrity?) but didn't find much besides it saying if have to add myself to Access-Control-Allow-Origin on the server (but I cannot edit the settings of my school server.)



How do I add these credentials? Will I continue to get a CORS error. Sorry if this is a waste of your time, don't know too much about stack overflow



*EDIT
I have my react app in which my only component right now will be some login stuff. It is called Login.JS. Right now all I want it to do is get the data from the database on submit of the form. Here is my code.



import React from 'react';

class Login extends React.Component{
constructor (props) {
super(props);

this.state = {
userName: "",
password: "",
hits: ,
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange = event => {
this.setState({
[event.target.name]: event.target.value
});
}

handleSubmit(e) {
console.log(e);
e.preventDefault();
this.updateFromDB();
}

formValidation() {
return this.state.password.length > 0 && this.state.userName.length > 0;
}

updateFromDB(){
let API = "THE_URL_FOR_MY_DATABASE";
let query = "SELECT * FROM karrsen_test";
fetch(API + query, {
method: 'POST',
mode: 'cors'
})
.then(response => response.json())
.then(data => this.setState({ hits: data.hits }));
}

render (){
return(
<div className= "Login-form">
<form onSubmit = {(e) => this.handleSubmit(e)}>
<label>
Username:
<input
type = "text"
value = {this.state.userName}
onChange = {this.handleChange}
name = "userName"/>
</label>
<label>
Password:
<input
type = "text"
value = {this.state.password}
onChange = {this.handleChange}
name = "password" />
</label>
<input
disabled = {!this.formValidation()}
type = "submit" />
</form>
</div>
)

}
}

export default Login;









share|improve this question




















  • 1




    Hi Karrsen, welcome to SO! Do you mind editing your question to include the specific error you are getting? Also, do you mind showing the part of your code where you use fetch? Thanks!
    – Matthew Herbst
    Nov 20 at 1:36










  • Of course! One minute. Should have done that to begin with! My apologies.
    – Karrsen B
    Nov 20 at 1:39















up vote
2
down vote

favorite












I have done hours of research on this and just can't find the answer I need. Sorry if this has been asked and I have been bad in my research, if so just link the helpful stack overflow page and I'll be on my merry way. Here is the summary of my problem.



I am in a CS4 class and we are designing our own webpage and must use our school's server for database storage. We learned php and how to use mySQL and our POST and GET requests for the server would look like this (written in PHP):



require("config.php");

$db = new PDO("mysql:dbname=" . $GLOBALS["database"] . ";host=" . $GLOBALS["hostname"] . ";port=" . $GLOBALS["port"],
$GLOBALS["username"], $GLOBALS["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT * FROM Karrsen_ajaxtest";
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetchAll();
foreach ($rows as $row) {
print(strip_tags($row['name']) . "<br/>");
}


Where the config was set correctly.



Now I am doing my final project it React.js and have to request from the same server. I want to use the built in Fetch system but it throws CORS errors and I also don't know how to add the aforementioned username, password, database, and hostname. I have looked through the MDN webdocs thoroughly (thought it might be request Header, Credentials, Mode, or Integrity?) but didn't find much besides it saying if have to add myself to Access-Control-Allow-Origin on the server (but I cannot edit the settings of my school server.)



How do I add these credentials? Will I continue to get a CORS error. Sorry if this is a waste of your time, don't know too much about stack overflow



*EDIT
I have my react app in which my only component right now will be some login stuff. It is called Login.JS. Right now all I want it to do is get the data from the database on submit of the form. Here is my code.



import React from 'react';

class Login extends React.Component{
constructor (props) {
super(props);

this.state = {
userName: "",
password: "",
hits: ,
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange = event => {
this.setState({
[event.target.name]: event.target.value
});
}

handleSubmit(e) {
console.log(e);
e.preventDefault();
this.updateFromDB();
}

formValidation() {
return this.state.password.length > 0 && this.state.userName.length > 0;
}

updateFromDB(){
let API = "THE_URL_FOR_MY_DATABASE";
let query = "SELECT * FROM karrsen_test";
fetch(API + query, {
method: 'POST',
mode: 'cors'
})
.then(response => response.json())
.then(data => this.setState({ hits: data.hits }));
}

render (){
return(
<div className= "Login-form">
<form onSubmit = {(e) => this.handleSubmit(e)}>
<label>
Username:
<input
type = "text"
value = {this.state.userName}
onChange = {this.handleChange}
name = "userName"/>
</label>
<label>
Password:
<input
type = "text"
value = {this.state.password}
onChange = {this.handleChange}
name = "password" />
</label>
<input
disabled = {!this.formValidation()}
type = "submit" />
</form>
</div>
)

}
}

export default Login;









share|improve this question




















  • 1




    Hi Karrsen, welcome to SO! Do you mind editing your question to include the specific error you are getting? Also, do you mind showing the part of your code where you use fetch? Thanks!
    – Matthew Herbst
    Nov 20 at 1:36










  • Of course! One minute. Should have done that to begin with! My apologies.
    – Karrsen B
    Nov 20 at 1:39













up vote
2
down vote

favorite









up vote
2
down vote

favorite











I have done hours of research on this and just can't find the answer I need. Sorry if this has been asked and I have been bad in my research, if so just link the helpful stack overflow page and I'll be on my merry way. Here is the summary of my problem.



I am in a CS4 class and we are designing our own webpage and must use our school's server for database storage. We learned php and how to use mySQL and our POST and GET requests for the server would look like this (written in PHP):



require("config.php");

$db = new PDO("mysql:dbname=" . $GLOBALS["database"] . ";host=" . $GLOBALS["hostname"] . ";port=" . $GLOBALS["port"],
$GLOBALS["username"], $GLOBALS["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT * FROM Karrsen_ajaxtest";
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetchAll();
foreach ($rows as $row) {
print(strip_tags($row['name']) . "<br/>");
}


Where the config was set correctly.



Now I am doing my final project it React.js and have to request from the same server. I want to use the built in Fetch system but it throws CORS errors and I also don't know how to add the aforementioned username, password, database, and hostname. I have looked through the MDN webdocs thoroughly (thought it might be request Header, Credentials, Mode, or Integrity?) but didn't find much besides it saying if have to add myself to Access-Control-Allow-Origin on the server (but I cannot edit the settings of my school server.)



How do I add these credentials? Will I continue to get a CORS error. Sorry if this is a waste of your time, don't know too much about stack overflow



*EDIT
I have my react app in which my only component right now will be some login stuff. It is called Login.JS. Right now all I want it to do is get the data from the database on submit of the form. Here is my code.



import React from 'react';

class Login extends React.Component{
constructor (props) {
super(props);

this.state = {
userName: "",
password: "",
hits: ,
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange = event => {
this.setState({
[event.target.name]: event.target.value
});
}

handleSubmit(e) {
console.log(e);
e.preventDefault();
this.updateFromDB();
}

formValidation() {
return this.state.password.length > 0 && this.state.userName.length > 0;
}

updateFromDB(){
let API = "THE_URL_FOR_MY_DATABASE";
let query = "SELECT * FROM karrsen_test";
fetch(API + query, {
method: 'POST',
mode: 'cors'
})
.then(response => response.json())
.then(data => this.setState({ hits: data.hits }));
}

render (){
return(
<div className= "Login-form">
<form onSubmit = {(e) => this.handleSubmit(e)}>
<label>
Username:
<input
type = "text"
value = {this.state.userName}
onChange = {this.handleChange}
name = "userName"/>
</label>
<label>
Password:
<input
type = "text"
value = {this.state.password}
onChange = {this.handleChange}
name = "password" />
</label>
<input
disabled = {!this.formValidation()}
type = "submit" />
</form>
</div>
)

}
}

export default Login;









share|improve this question















I have done hours of research on this and just can't find the answer I need. Sorry if this has been asked and I have been bad in my research, if so just link the helpful stack overflow page and I'll be on my merry way. Here is the summary of my problem.



I am in a CS4 class and we are designing our own webpage and must use our school's server for database storage. We learned php and how to use mySQL and our POST and GET requests for the server would look like this (written in PHP):



require("config.php");

$db = new PDO("mysql:dbname=" . $GLOBALS["database"] . ";host=" . $GLOBALS["hostname"] . ";port=" . $GLOBALS["port"],
$GLOBALS["username"], $GLOBALS["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT * FROM Karrsen_ajaxtest";
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetchAll();
foreach ($rows as $row) {
print(strip_tags($row['name']) . "<br/>");
}


Where the config was set correctly.



Now I am doing my final project it React.js and have to request from the same server. I want to use the built in Fetch system but it throws CORS errors and I also don't know how to add the aforementioned username, password, database, and hostname. I have looked through the MDN webdocs thoroughly (thought it might be request Header, Credentials, Mode, or Integrity?) but didn't find much besides it saying if have to add myself to Access-Control-Allow-Origin on the server (but I cannot edit the settings of my school server.)



How do I add these credentials? Will I continue to get a CORS error. Sorry if this is a waste of your time, don't know too much about stack overflow



*EDIT
I have my react app in which my only component right now will be some login stuff. It is called Login.JS. Right now all I want it to do is get the data from the database on submit of the form. Here is my code.



import React from 'react';

class Login extends React.Component{
constructor (props) {
super(props);

this.state = {
userName: "",
password: "",
hits: ,
};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange = event => {
this.setState({
[event.target.name]: event.target.value
});
}

handleSubmit(e) {
console.log(e);
e.preventDefault();
this.updateFromDB();
}

formValidation() {
return this.state.password.length > 0 && this.state.userName.length > 0;
}

updateFromDB(){
let API = "THE_URL_FOR_MY_DATABASE";
let query = "SELECT * FROM karrsen_test";
fetch(API + query, {
method: 'POST',
mode: 'cors'
})
.then(response => response.json())
.then(data => this.setState({ hits: data.hits }));
}

render (){
return(
<div className= "Login-form">
<form onSubmit = {(e) => this.handleSubmit(e)}>
<label>
Username:
<input
type = "text"
value = {this.state.userName}
onChange = {this.handleChange}
name = "userName"/>
</label>
<label>
Password:
<input
type = "text"
value = {this.state.password}
onChange = {this.handleChange}
name = "password" />
</label>
<input
disabled = {!this.formValidation()}
type = "submit" />
</form>
</div>
)

}
}

export default Login;






php mysql reactjs fetch






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 19:38









Matthew Herbst

9,972134485




9,972134485










asked Nov 20 at 1:32









Karrsen B

183




183








  • 1




    Hi Karrsen, welcome to SO! Do you mind editing your question to include the specific error you are getting? Also, do you mind showing the part of your code where you use fetch? Thanks!
    – Matthew Herbst
    Nov 20 at 1:36










  • Of course! One minute. Should have done that to begin with! My apologies.
    – Karrsen B
    Nov 20 at 1:39














  • 1




    Hi Karrsen, welcome to SO! Do you mind editing your question to include the specific error you are getting? Also, do you mind showing the part of your code where you use fetch? Thanks!
    – Matthew Herbst
    Nov 20 at 1:36










  • Of course! One minute. Should have done that to begin with! My apologies.
    – Karrsen B
    Nov 20 at 1:39








1




1




Hi Karrsen, welcome to SO! Do you mind editing your question to include the specific error you are getting? Also, do you mind showing the part of your code where you use fetch? Thanks!
– Matthew Herbst
Nov 20 at 1:36




Hi Karrsen, welcome to SO! Do you mind editing your question to include the specific error you are getting? Also, do you mind showing the part of your code where you use fetch? Thanks!
– Matthew Herbst
Nov 20 at 1:36












Of course! One minute. Should have done that to begin with! My apologies.
– Karrsen B
Nov 20 at 1:39




Of course! One minute. Should have done that to begin with! My apologies.
– Karrsen B
Nov 20 at 1:39












1 Answer
1






active

oldest

votes

















up vote
2
down vote













CORS is enabled by default with fetch, but your server will need to be configured to handle cross origin requests.



Assuming your school's server is running Apache, you should be able to do that by adding an .htaccess file to your PHP directory. Simply name the file .htaccess and add the following line.



Header set Access-Control-Allow-Origin "*"


This requires the Apache server to be configured to allow overrides in the DocumentRoot. The DocumentRoot is the root directory that Apache is hosting. For example, say you're hosting example.com from the /var/www/example directory. /var/www/example is the DocumentRoot.



In the Apache configuration for example.com, the AllowOverride directive must be set to allow the .htaccess file to override the base configuration - otherwise the .htaccess file is ignored.



To enable Apache to control and modify HTTP request and response headers, the mod_headers module must be enabled. From a terminal, enter the following command.



a2enmod headers


If all else fails, you can try editing the response (from the server) HTTP header with PHP, by adding the following line to your PHP script - probably at the top before anything else.



header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");





share|improve this answer























  • I was going to write the same answer. CORS should be enabled in the server to allow fetching from a different domain.
    – Dinesh Pandiyan
    Nov 20 at 2:02










  • Sure seems like that's the issue @DineshPandiyan, but I'm making the assumption the school is using a LAMP server - odds are. But the same concept would apply to any Web server that I'm aware of.
    – Jason
    Nov 20 at 2:04










  • Cors is not always the default (it's never the default in Chrome for example), and you should always make sure to set mode: 'cors' when using fetch if that is what you want: developer.mozilla.org/en-US/docs/Web/API/Request/Request
    – Matthew Herbst
    Nov 20 at 2:37






  • 1




    @Jason Microsoft and MDN are disagreeing. I tend to trust MDN. Of course, only one of the two can be correct. The official spec (we all know browsers are 100% spec-compliant, right!? :D) says: "A request has an associated mode, which is "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless stated otherwise, it is "no-cors".
    – Matthew Herbst
    Nov 20 at 2:46






  • 1




    @MatthewHerbst given the conflict, and cross-browser issues, I'd say it couldn't hurt - and may help - to set the fetch to explicitly use CORS. Thanks!
    – Jason
    Nov 20 at 2:53











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384998%2fusing-fetch-in-react-need-username-password-to-access-database%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote













CORS is enabled by default with fetch, but your server will need to be configured to handle cross origin requests.



Assuming your school's server is running Apache, you should be able to do that by adding an .htaccess file to your PHP directory. Simply name the file .htaccess and add the following line.



Header set Access-Control-Allow-Origin "*"


This requires the Apache server to be configured to allow overrides in the DocumentRoot. The DocumentRoot is the root directory that Apache is hosting. For example, say you're hosting example.com from the /var/www/example directory. /var/www/example is the DocumentRoot.



In the Apache configuration for example.com, the AllowOverride directive must be set to allow the .htaccess file to override the base configuration - otherwise the .htaccess file is ignored.



To enable Apache to control and modify HTTP request and response headers, the mod_headers module must be enabled. From a terminal, enter the following command.



a2enmod headers


If all else fails, you can try editing the response (from the server) HTTP header with PHP, by adding the following line to your PHP script - probably at the top before anything else.



header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");





share|improve this answer























  • I was going to write the same answer. CORS should be enabled in the server to allow fetching from a different domain.
    – Dinesh Pandiyan
    Nov 20 at 2:02










  • Sure seems like that's the issue @DineshPandiyan, but I'm making the assumption the school is using a LAMP server - odds are. But the same concept would apply to any Web server that I'm aware of.
    – Jason
    Nov 20 at 2:04










  • Cors is not always the default (it's never the default in Chrome for example), and you should always make sure to set mode: 'cors' when using fetch if that is what you want: developer.mozilla.org/en-US/docs/Web/API/Request/Request
    – Matthew Herbst
    Nov 20 at 2:37






  • 1




    @Jason Microsoft and MDN are disagreeing. I tend to trust MDN. Of course, only one of the two can be correct. The official spec (we all know browsers are 100% spec-compliant, right!? :D) says: "A request has an associated mode, which is "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless stated otherwise, it is "no-cors".
    – Matthew Herbst
    Nov 20 at 2:46






  • 1




    @MatthewHerbst given the conflict, and cross-browser issues, I'd say it couldn't hurt - and may help - to set the fetch to explicitly use CORS. Thanks!
    – Jason
    Nov 20 at 2:53















up vote
2
down vote













CORS is enabled by default with fetch, but your server will need to be configured to handle cross origin requests.



Assuming your school's server is running Apache, you should be able to do that by adding an .htaccess file to your PHP directory. Simply name the file .htaccess and add the following line.



Header set Access-Control-Allow-Origin "*"


This requires the Apache server to be configured to allow overrides in the DocumentRoot. The DocumentRoot is the root directory that Apache is hosting. For example, say you're hosting example.com from the /var/www/example directory. /var/www/example is the DocumentRoot.



In the Apache configuration for example.com, the AllowOverride directive must be set to allow the .htaccess file to override the base configuration - otherwise the .htaccess file is ignored.



To enable Apache to control and modify HTTP request and response headers, the mod_headers module must be enabled. From a terminal, enter the following command.



a2enmod headers


If all else fails, you can try editing the response (from the server) HTTP header with PHP, by adding the following line to your PHP script - probably at the top before anything else.



header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");





share|improve this answer























  • I was going to write the same answer. CORS should be enabled in the server to allow fetching from a different domain.
    – Dinesh Pandiyan
    Nov 20 at 2:02










  • Sure seems like that's the issue @DineshPandiyan, but I'm making the assumption the school is using a LAMP server - odds are. But the same concept would apply to any Web server that I'm aware of.
    – Jason
    Nov 20 at 2:04










  • Cors is not always the default (it's never the default in Chrome for example), and you should always make sure to set mode: 'cors' when using fetch if that is what you want: developer.mozilla.org/en-US/docs/Web/API/Request/Request
    – Matthew Herbst
    Nov 20 at 2:37






  • 1




    @Jason Microsoft and MDN are disagreeing. I tend to trust MDN. Of course, only one of the two can be correct. The official spec (we all know browsers are 100% spec-compliant, right!? :D) says: "A request has an associated mode, which is "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless stated otherwise, it is "no-cors".
    – Matthew Herbst
    Nov 20 at 2:46






  • 1




    @MatthewHerbst given the conflict, and cross-browser issues, I'd say it couldn't hurt - and may help - to set the fetch to explicitly use CORS. Thanks!
    – Jason
    Nov 20 at 2:53













up vote
2
down vote










up vote
2
down vote









CORS is enabled by default with fetch, but your server will need to be configured to handle cross origin requests.



Assuming your school's server is running Apache, you should be able to do that by adding an .htaccess file to your PHP directory. Simply name the file .htaccess and add the following line.



Header set Access-Control-Allow-Origin "*"


This requires the Apache server to be configured to allow overrides in the DocumentRoot. The DocumentRoot is the root directory that Apache is hosting. For example, say you're hosting example.com from the /var/www/example directory. /var/www/example is the DocumentRoot.



In the Apache configuration for example.com, the AllowOverride directive must be set to allow the .htaccess file to override the base configuration - otherwise the .htaccess file is ignored.



To enable Apache to control and modify HTTP request and response headers, the mod_headers module must be enabled. From a terminal, enter the following command.



a2enmod headers


If all else fails, you can try editing the response (from the server) HTTP header with PHP, by adding the following line to your PHP script - probably at the top before anything else.



header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");





share|improve this answer














CORS is enabled by default with fetch, but your server will need to be configured to handle cross origin requests.



Assuming your school's server is running Apache, you should be able to do that by adding an .htaccess file to your PHP directory. Simply name the file .htaccess and add the following line.



Header set Access-Control-Allow-Origin "*"


This requires the Apache server to be configured to allow overrides in the DocumentRoot. The DocumentRoot is the root directory that Apache is hosting. For example, say you're hosting example.com from the /var/www/example directory. /var/www/example is the DocumentRoot.



In the Apache configuration for example.com, the AllowOverride directive must be set to allow the .htaccess file to override the base configuration - otherwise the .htaccess file is ignored.



To enable Apache to control and modify HTTP request and response headers, the mod_headers module must be enabled. From a terminal, enter the following command.



a2enmod headers


If all else fails, you can try editing the response (from the server) HTTP header with PHP, by adding the following line to your PHP script - probably at the top before anything else.



header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 26 at 18:28

























answered Nov 20 at 1:41









Jason

817




817












  • I was going to write the same answer. CORS should be enabled in the server to allow fetching from a different domain.
    – Dinesh Pandiyan
    Nov 20 at 2:02










  • Sure seems like that's the issue @DineshPandiyan, but I'm making the assumption the school is using a LAMP server - odds are. But the same concept would apply to any Web server that I'm aware of.
    – Jason
    Nov 20 at 2:04










  • Cors is not always the default (it's never the default in Chrome for example), and you should always make sure to set mode: 'cors' when using fetch if that is what you want: developer.mozilla.org/en-US/docs/Web/API/Request/Request
    – Matthew Herbst
    Nov 20 at 2:37






  • 1




    @Jason Microsoft and MDN are disagreeing. I tend to trust MDN. Of course, only one of the two can be correct. The official spec (we all know browsers are 100% spec-compliant, right!? :D) says: "A request has an associated mode, which is "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless stated otherwise, it is "no-cors".
    – Matthew Herbst
    Nov 20 at 2:46






  • 1




    @MatthewHerbst given the conflict, and cross-browser issues, I'd say it couldn't hurt - and may help - to set the fetch to explicitly use CORS. Thanks!
    – Jason
    Nov 20 at 2:53


















  • I was going to write the same answer. CORS should be enabled in the server to allow fetching from a different domain.
    – Dinesh Pandiyan
    Nov 20 at 2:02










  • Sure seems like that's the issue @DineshPandiyan, but I'm making the assumption the school is using a LAMP server - odds are. But the same concept would apply to any Web server that I'm aware of.
    – Jason
    Nov 20 at 2:04










  • Cors is not always the default (it's never the default in Chrome for example), and you should always make sure to set mode: 'cors' when using fetch if that is what you want: developer.mozilla.org/en-US/docs/Web/API/Request/Request
    – Matthew Herbst
    Nov 20 at 2:37






  • 1




    @Jason Microsoft and MDN are disagreeing. I tend to trust MDN. Of course, only one of the two can be correct. The official spec (we all know browsers are 100% spec-compliant, right!? :D) says: "A request has an associated mode, which is "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless stated otherwise, it is "no-cors".
    – Matthew Herbst
    Nov 20 at 2:46






  • 1




    @MatthewHerbst given the conflict, and cross-browser issues, I'd say it couldn't hurt - and may help - to set the fetch to explicitly use CORS. Thanks!
    – Jason
    Nov 20 at 2:53
















I was going to write the same answer. CORS should be enabled in the server to allow fetching from a different domain.
– Dinesh Pandiyan
Nov 20 at 2:02




I was going to write the same answer. CORS should be enabled in the server to allow fetching from a different domain.
– Dinesh Pandiyan
Nov 20 at 2:02












Sure seems like that's the issue @DineshPandiyan, but I'm making the assumption the school is using a LAMP server - odds are. But the same concept would apply to any Web server that I'm aware of.
– Jason
Nov 20 at 2:04




Sure seems like that's the issue @DineshPandiyan, but I'm making the assumption the school is using a LAMP server - odds are. But the same concept would apply to any Web server that I'm aware of.
– Jason
Nov 20 at 2:04












Cors is not always the default (it's never the default in Chrome for example), and you should always make sure to set mode: 'cors' when using fetch if that is what you want: developer.mozilla.org/en-US/docs/Web/API/Request/Request
– Matthew Herbst
Nov 20 at 2:37




Cors is not always the default (it's never the default in Chrome for example), and you should always make sure to set mode: 'cors' when using fetch if that is what you want: developer.mozilla.org/en-US/docs/Web/API/Request/Request
– Matthew Herbst
Nov 20 at 2:37




1




1




@Jason Microsoft and MDN are disagreeing. I tend to trust MDN. Of course, only one of the two can be correct. The official spec (we all know browsers are 100% spec-compliant, right!? :D) says: "A request has an associated mode, which is "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless stated otherwise, it is "no-cors".
– Matthew Herbst
Nov 20 at 2:46




@Jason Microsoft and MDN are disagreeing. I tend to trust MDN. Of course, only one of the two can be correct. The official spec (we all know browsers are 100% spec-compliant, right!? :D) says: "A request has an associated mode, which is "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless stated otherwise, it is "no-cors".
– Matthew Herbst
Nov 20 at 2:46




1




1




@MatthewHerbst given the conflict, and cross-browser issues, I'd say it couldn't hurt - and may help - to set the fetch to explicitly use CORS. Thanks!
– Jason
Nov 20 at 2:53




@MatthewHerbst given the conflict, and cross-browser issues, I'd say it couldn't hurt - and may help - to set the fetch to explicitly use CORS. Thanks!
– Jason
Nov 20 at 2:53


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384998%2fusing-fetch-in-react-need-username-password-to-access-database%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin